【问题标题】:use .split() for files. java对文件使用 .split()。爪哇
【发布时间】:2022-10-02 21:22:11
【问题描述】:

我有一个文件,想逐行拆分文件。但我不想每次都创建一个新文件。只需将每一行存储在一个数组中。 .split() 方法正是我想要的,但它不能用于文件。

import java.io.File;
import java.io.FileNotFoundException;

class Read{

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


            myReader.close();


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

  • 也许BufferedReader.lines() 后跟Stream.toArray() - 或Files.readAllLines()List.toArray()(如果确实需要数组)
  • \"want to create a new file each time\"- 但你只是在你的代码中读取一个文件,并且不是创建一个新文件或写任何东西。您至少需要用伪代码描述您的意图。是否要将文件的每一行拆分为多行,然后将这些数据写入新创建的文件中?

标签: java arrays split


【解决方案1】:

java.nio.file.Files#readAllLines(java.nio.file.Path) 方法:

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

java.nio.file.Files#lines(java.nio.file.Path)(你可以获取一个流,然后将其转换为一个数组):

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

文件:

Files#readAllLines

Files#lines

【讨论】:

  • 我现在无法测试。但是非常感谢你的提议。这是否在每一行上拆分文件并将每一行存储在数组中?
【解决方案2】:

您甚至没有在链接的代码中使用扫描仪。

如果您需要使用 Scanner 来执行此操作,则可以使用以下代码的变体。虽然我建议使用 star67 的解决方案,然后使用 .toArray(new String[0]);称呼。

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]);

【讨论】:

  • 如果你这样做,我建议Scanner 使用Path-constructor,并在try-with-resources 块中创建它,即try (Scanner sc = new Scanner(Paths.of("file.txt")) { ... }
  • 我相信#of 方法仅在“Path”类而不是“Paths”中可用,并且是在 Java 11 中引入的。Paths 有一个非常相似的方法,称为 #get,可以从 Java 7 开始使用。
  • 你说得对,我的意思是Paths.get()。我的建议成立。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
相关资源
最近更新 更多