Home > front end >  use .split() for files. java
use .split() for files. java

Time:09-16

I have a file and want to split the file line by line. But I do not want to create a new file each time. just store every line in an Array. the .split() method is exactly what I want but it can't be used for files.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

class Read{

    public static void main(String args[])
    {
        try{
            File datei = new File("file.txt");
            Scanner myReader = new Scanner(datei);
            String[] splitDatei = datei.split(System.lineSeparator());


            myReader.close();


        }catch(FileNotFoundException e){
            System.out.println("");
            e.printStackTrace();
        }
    }
}

CodePudding user response:

There is java.nio.file.Files#readAllLines(java.nio.file.Path) method:

List<String> stringList = Files.readAllLines(Path.of("file.txt"));

or java.nio.file.Files#lines(java.nio.file.Path) (you can can get a stream and then convert it to an array):

try (Stream<String> stream = Files.lines(Path.of("file.txt"))) {
    String[] strings = stream.toArray(String[]::new);
} catch (IOException e) {
    //
}

Docs:

Files#readAllLines

Files#lines

CodePudding user response:

It doesn't even appear that you are making use of your scanner in the code that you linked.

If you need to use the Scanner to do it, then you can use a variation of the following code. Though I recommend using star67's solution followed by a .toArray(new String[0]); call.

List<String> lines = new ArrayList<>();
File datei = new File("file.txt");
Scanner myReader = new Scanner(datei);
while(myReader.hasNextLine())
{
    lines.add(myReader.nextLine());
}
myReader.close();
final String[] linesArray = lines.toArray(new String[0]);
  • Related