简体   繁体   中英

Read file from txt to integer array line by line

i have a text file that look like this:

1 2 3 4 5 8 
12 22 5 33 11 56
5 2 3 45 89 45

i included a code that I tried but didn't work because every time the line looks like it's empty when i try to print the line to console.

i try read the file with ArrayList but is not working.

BufferedReader bufReader = new BufferedReader(new 
FileReader("file1.txt"));
    ArrayList<String> listOfLines = new ArrayList<>();
    String line = bufReader.readLine();
    while (line != null) {
      listOfLines.add(line);
      line = bufReader.readLine();
      System.out.println("full: " + line);
      System.out.print("0: " + line.charAt(0));    
    }

i want to read from file to a array line by line, for example: [12][22][5][33][11][56]

You could use streams:

Files.lines(Paths.get("file.txt"))
    .map(line -> Arrays.stream(line.split(" "))
        .map(Integer::valueOf)
        .collect(Collectors.toList()))
    .collect(Collectors.toList())

This will return a List<List<Integer>> with all elements as integers. If you just want to print all elements for each line, then you could replace the last line with .forEach(System.out::println) .

If you want to read the file into one array per line you can use this code:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ReadIntArrayFromFile {

    public static void main(String[] args) throws IOException {
        //enter your path to the file here
        File file = new File("src/main/java/integer_array_from_file/file.txt");
        //read the lines from the file
        List<String> lines = Files.readAllLines(file.toPath());

        //create a list of arrays (one array per line)
        List<int[]> arrayForEachLine = new ArrayList<int[]>(lines.size());
        for (String line : lines) {
            //create the array from the line (one array for each line)
            int[] array = Stream.of(line.split(" ")).mapToInt(Integer::parseInt).toArray();
            //add the array to the list
            arrayForEachLine.add(array);
        }

        //print the arrays
        arrayForEachLine.stream().map(array -> Arrays.toString(array)).forEach(System.out::println);
    }
}

The output (for the example file content in your question) is:

[1, 2, 3, 4, 5, 8]
[12, 22, 5, 33, 11, 56]
[5, 2, 3, 45, 89, 45]

Try this code

final String dataFilePath = "C:\\Users\\Desktop\\txt.txt";
            ArrayList<String> listOfLines = new ArrayList<>();
           List listOfLinesint = new ArrayList<>();
                    BufferedReader reader;
                    try {
                        reader = new BufferedReader(new FileReader(dataFilePath));
                        String line = reader.readLine();
                        while (line != null) {
                            //System.out.println(line);
                            listOfLinesint.add(line);
                            line = reader.readLine();
                        }
                        reader.close();
                        System.out.println(listOfLinesint);
                    } 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