简体   繁体   中英

Reading txt files in Java

I have program that has a section that requires me to read and append items to a txt file. I know how to do basic reading and appending but I am confused as to how I would read every 4th line in a txt file and then store it in a variable. Or even every alternate line. Also, if there are double valued numbers, can I read it as a number and not a string?

To read say every fourth line from a text file you would read a line and update a counter. When the counter reaches 4 , you save the line in a String variable. Something like this would do the job:

import java.io.*;
public class SkipLineReader {

    public static void main(String[] args) throws IOException {
        String line = "";
        String savedLine = "";
        int counter = 0;
        FileInputStream fin = new FileInputStream("text_file.txt");
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(fin));
        
        // Save every fourth line
        while( (line = bufIn.readLine()) != null) {
            counter++;
            if( counter == 4 ) {
                savedLine = line;
                System.out.println(line);
            }
        }
    }
    
}

To save every alternate line, you would save the line every time the counter reaches two and then reset the counter back to zero. Like this:

        // Save every alternate line
        while( (line = bufIn.readLine()) != null) {
            counter++;
            if( counter % 2 == 0 ) {
                counter = 0;
                savedLine = line;
                System.out.println(line);
            }
        }

As for reading doubles from a file, you could do it with a BufferedReader and then use Double's parseDouble(string) method to retrieve the double value, but a better method is to use the Scanner object in java.util . The constructor for this class will accept a FileInputStream and there is a nextDouble() method that you can use to read a double value.

Here's some code that illustrates using a Scanner object to grab double values from a String (to read from a file, supply a FileInputStream into the Scanner class's constructor):

import java.util.*;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6 true";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // use US locale to be able to identify doubles in the string
      scanner.useLocale(Locale.US);

      // find the next double token and print it
      // loop for the whole scanner
      while (scanner.hasNext()) {

         // if the next is a double, print found and the double
         if (scanner.hasNextDouble()) {
            System.out.println("Found :" + scanner.nextDouble());
         }

         // if a double is not found, print "Not Found" and the token
         System.out.println("Not Found :" + scanner.next());
      }

      // close the scanner
      scanner.close();
   }
}

This is my code example.

public static void main(String[] args) throws Exception {
    // Read file by BufferedReader line by line.
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader("test.txt"));
        String line = reader.readLine();
        while (line != null) {
            line = line.trim();
            System.out.println(line);
            
            // Using regular expression to check line is valid number
            if (!line.trim().equals("") && line.trim().matches("^\\d+||^\\d+(\\.)\\d+$")) {
                double value = Double.valueOf(line.trim());
                System.out.println(value);
            } else {
                String value = line.trim();
                System.out.println(value);
            }
            
            // Read next line
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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