简体   繁体   中英

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

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];
}

You can delimit by whitespace and

    Scanner scanner = new Scanner(new File("."));
    while (scanner.hasNext()) {

        //If both on different lines
        c = scanner.next().charAt(0);
        d = scanner.nextDouble();

        //if both on same line
        String s = scanner.next();
        String[] splits = s.split("\\s+");
        if (splits.length == 2) {
            c = splits[0].charAt(0);
            d = Double.parseDouble(splits[1]);
        }
    }
    scanner.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM