Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in a txt file

Tags:

java

I'm trying to read in from whats on the first two lines of a txt file, put it on a string and pass that string onto my methods. I'm confused on what I need to do in the main method.

Heres what I have:

    public class TestingClass  {
Stacked s;// = new Stacked(100);
 String Finame;

public TestingClass(Stacked stack) {
    //Stacked s = new Stacked(100);
    s = stack;
    getFileName();
    readFileContents(); 
}

public void readFileContents() {
    boolean looping;
    DataInputStream in;
    String line = "" ;
    int j, len;
    char ch;

    try {
        in = new DataInputStream(new FileInputStream(Finame));
        len = line.length();
        for(j = 0; j<len; j++) {
                System.out.println("line["+j+"] = "+line.charAt(j));
        }
    } 

    catch(IOException e) {
            System.out.println("error " + e);
    }
}   

public void getFileName() {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter File Name");
    Finame = in.nextLine();
    System.out.println("You Entered " + Finame);
}

       public static void main(String[] args) {
         Stacked st = new Stacked(100);
         TestingClass clas = new TestingClass(st);
         //String y = new String("(z * j)/(b * 8) ^2");
         // clas.test(y);

       }

I tried String x = new String(x.getNewFile()) I'm not sure if thats the right way to go with that or not.

like image 975
TMan Avatar asked Sep 17 '11 22:09

TMan


People also ask

How do I read data from a text file?

To read from a text fileUse the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.

How do I read a text file in Word?

Open a file in read mode which contains a string. Use for loop to read each line from the text file. Again use for loop to read each word from the line splitted by ' '. Display each word from each line in the text file.

Can Python read TXT files?

In Python, there are a few ways you can read a text file. In this article, I will go over the open() function, the read() , readline() , readlines() , close() methods, and the with keyword.


1 Answers

Try this:

File file = new File("file.txt");

BufferedReader reader = new BufferedReader(new FileReader(file));
String line1 = reader.readLine();
String line2 = reader.readLine();
like image 87
Justin Avatar answered Sep 20 '22 05:09

Justin