Java: How to read a text file

后端 未结 9 2295
青春惊慌失措
青春惊慌失措 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: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 lines = Files.readAllLines(file, StandardCharsets.UTF_8);
    

提交回复
热议问题