Home > Net >  How to read all lines from a java file and split the elements that are divided by a specific symbol
How to read all lines from a java file and split the elements that are divided by a specific symbol

Time:12-19

For my project I need to read every line in a text file. The elements in this file are divided with a ";". I need to save the result of this FileReader into a String array. What's also important is that after every line I need some sort of linebreaker/divider.

I currently have this:

Path path = Paths.get("src/main/resources", "crochet.txt");
String[] result = new String[0];

if (Files.exists(path)) {
    var lines = Files.readAllLines(path);
    for (String line : lines) {
        result = lines.get(0).split(";");
    }
} else {
    System.err.println("Error: File not found: "   path.toAbsolutePath());
}
return result;

And in the main class:

FileHandler fileHandler = new FileHandler();
fileHandler.readFile();

String[] input = fileHandler.readFile();

This only reads the first line in the file and also doesn't add a linebreak to the array.

CodePudding user response:

To read each line from a text file and save each line to an array of strings, with a line separator after each line, you can use the following code:

Path path = Paths.get("src/main/resources", "crochet.txt");
List<String> result = new ArrayList<>();

if (Files.exists(path)) {
var lines = Files.readAllLines(path);
for (String line : lines) {
    result.add(line);
    result.add("\n"); // ajoute un séparateur de ligne
}
} else {
System.err.println("Error: File not found: "   path.toAbsolutePath());
}

// convertit la liste en tableau de chaînes de caractères
String[] input = result.toArray(new String[0]);
return input;

You can use this code in your main class as follows:

FileHandler fileHandler = new FileHandler();
String[] input = fileHandler.readFile();

CodePudding user response:

You can try using Files.lines(Path path) method that returns Stream<String>, then using map method, split and collect the result.

here is the code snippet. ( of course, you need to handle file exists conditions etc.)

List<String[]> linesSplit = Files.lines(Path.of("/path/to/file"))
                .map(line -> line.split(";"))
                .collect(Collectors.toList());
  •  Tags:  
  • java
  • Related