javafilejava.util.scannerline-by-line

How do you read a text file, line by line, and separate contents of each line in Java?


I was wondering how to go about reading a file, and scanning each line, but separating the contents of each line into a Char variable and into a Double variable.

Example:

Let's say we write a code that opens up text file "Sample.txt". To read the first line you would use the following code:

 while(fin.hasNext())
         {

            try{

                inType2 = fin.next().charAt(0);

                inAmount2 = fin.nextDouble();
           }

This code basically says that if there is a next line, it will put the next char into inType2 and the next Double into inAmount2.

What if my txt file is written as follows:

D    100.00
E    54.54
T    90.99

How would I go about reading each line, putting "D" into the Char variable, and the corresponding Double or "100.00", in this example, into its Double variable.

I feel like the code I wrote reads the following txt files:

D
100.00
E
54.54
T
90.99

If you could please provide me with an efficient way to read lines from a file, and separate according to variable type, I'd greatly appreciate it. The Sample.txt will always have the char first, and the double second.

-Manny


Solution

  • Use BufferedReader to read line, and then split on whitespace.

    while((line=br.readLine())!=null){
        String[] arry = line.split("\\s+");
        inType2 = arry[0];
        inAmount2 = arry[1];
    }