Java: How to read a text file

后端 未结 9 2149
青春惊慌失措
青春惊慌失措 2020-11-22 06:58

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of t

相关标签:
9条回答
  • 2020-11-22 07:03

    You can use Files#readAllLines() to get all lines of a text file into a List<String>.

    for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
        // ...
    }
    

    Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files


    You can use String#split() to split a String in parts based on a regular expression.

    for (String part : line.split("\\s+")) {
        // ...
    }
    

    Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String


    You can use Integer#valueOf() to convert a String into an Integer.

    Integer i = Integer.valueOf(part);
    

    Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings


    You can use List#add() to add an element to a List.

    numbers.add(i);
    

    Tutorial: Interfaces > The List Interface


    So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

    List<Integer> numbers = new ArrayList<>();
    for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
        for (String part : line.split("\\s+")) {
            Integer i = Integer.valueOf(part);
            numbers.add(i);
        }
    }
    

    If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().

    List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
        .map(line -> line.split("\\s+")).flatMap(Arrays::stream)
        .map(Integer::valueOf)
        .collect(Collectors.toList());
    

    Tutorial: Processing data with Java 8 streams

    0 讨论(0)
  • 2020-11-22 07:03

    All the answers so far given involve reading the file line by line, taking the line in as a String, and then processing the String.

    There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it'll also be acceptable in terms of efficiency. But if the file is long, it's a very inefficient way to do it, for two reasons:

    1. Every character gets processed twice, once in constructing the String, and once in processing it.
    2. The garbage collector will not be your friend if there are lots of lines in the file. You're constructing a new String for each line, and then throwing it away when you move to the next line. The garbage collector will eventually have to dispose of all these String objects that you don't want any more. Someone's got to clean up after you.

    If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the List you're building.

    It will come out something like this:

    private List<Integer> readIntegers(File file) throws IOException {
        List<Integer> result = new ArrayList<>();
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        byte buf[] = new byte[16 * 1024];
        final FileChannel ch = raf.getChannel();
        int fileLength = (int) ch.size();
        final MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, 0,
                fileLength);
        int acc = 0;
        while (mb.hasRemaining()) {
            int len = Math.min(mb.remaining(), buf.length);
            mb.get(buf, 0, len);
            for (int i = 0; i < len; i++)
                if ((buf[i] >= 48) && (buf[i] <= 57))
                    acc = acc * 10 + buf[i] - 48;
                else {
                    result.add(acc);
                    acc = 0;
                }
        }
        ch.close();
        raf.close();
        return result;
    }
    

    The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn't a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn't.

    It's much, much faster than any of the String-based approaches also given as answers to this question. There is a detailed investigation of a very similar issue in this question. You'll see there that there's the possibility of improving it still further if you want to go down the multi-threaded line.

    0 讨论(0)
  • 2020-11-22 07:07

    This example code shows you how to read file in Java.

    import java.io.*;
    
    /**
     * This example code shows you how to read file in Java
     *
     * IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR   OWN      
     */
    
     public class ReadFileExample 
     {
        public static void main(String[] args) 
        {
           System.out.println("Reading File from Java code");
           //Name of the file
           String fileName="RAILWAY.txt";
           try{
    
              //Create object of FileReader
              FileReader inputFile = new FileReader(fileName);
    
              //Instantiate the BufferedReader Class
              BufferedReader bufferReader = new BufferedReader(inputFile);
    
              //Variable to hold the one line data
              String line;
    
              // Read file line by line and print on the console
              while ((line = bufferReader.readLine()) != null)   {
                System.out.println(line);
              }
              //Close the buffer reader
              bufferReader.close();
           }catch(Exception e){
              System.out.println("Error while reading file line by line:" + e.getMessage());                      
           }
    
         }
      }
    
    0 讨论(0)
  • 2020-11-22 07:10

    Use Apache Commons (IO and Lang) for simple/common things like this.

    Imports:

    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang3.ArrayUtils;
    

    Code:

    String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
    String[] array = ArrayUtils.toArray(contents.split(" "));
    

    Done.

    0 讨论(0)
  • 2020-11-22 07:10

    Using Java 7 to read files with NIO.2

    Import these packages:

    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    

    This is the process to read a file:

    Path file = Paths.get("C:\\Java\\file.txt");
    
    if(Files.exists(file) && Files.isReadable(file)) {
    
        try {
            // File reader
            BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
    
            String line;
            // read each line
            while((line = reader.readLine()) != null) {
                System.out.println(line);
                // tokenize each number
                StringTokenizer tokenizer = new StringTokenizer(line, " ");
                while (tokenizer.hasMoreElements()) {
                    // parse each integer in file
                    int element = Integer.parseInt(tokenizer.nextToken());
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    To read all lines of a file at once:

    Path file = Paths.get("C:\\Java\\file.txt");
    List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2020-11-22 07:20

    Java 1.5 introduced the Scanner class for handling input from file and streams.

    It is used for getting integers from a file and would look something like this:

    List<Integer> integers = new ArrayList<Integer>();
    Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
    while (fileScanner.hasNextInt()){
       integers.add(fileScanner.nextInt());
    }
    

    Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

    0 讨论(0)
提交回复
热议问题