如何在TX中将txt行复制到ArrayList中?

问题描述 投票:0回答:5

我正在尝试读取文本并将其拥有的每一行保存到ArrayList的新元素中。反正有没有继续读取和添加ArrayList,直到它到达文件的末尾或读者没有找到任何其他行读取?

此外,什么是最好的使用?扫描仪或BufferedReader?

java text arraylist
5个回答
1
投票

FWIW,如果您使用的是Java8,则可以使用流API,如下所示

public static void main(String[] args) throws IOException {

    String filename = "test.txt"; // Put your filename
    List fileLines = new ArrayList<>();

    // Make sure to add the "throws IOException" to the method  
    Stream<String> fileStream = Files.lines(Paths.get(filename));
    fileStream.forEach(fileLines::add);        
}

我在这里有一个main方法,只需将它放在你的方法中并添加throws语句或try-catch

您也可以将上面的内容转换为单行

((Stream<String>)Files.lines(Paths.get(filename))).forEach(fileLines::add);

2
投票

传统上,你会做这些操作:

  • 创建ScannerBufferedReader的实例
  • 设置条件以不断读取文件(使用Scanner,通过scanner.hasNextLine();使用BufferedReader,还有一些工作要做)
  • 从其中一行获取下一行并将其添加到列表中。

但是,使用Java 7的NIO库,您根本不需要这样做。

你可以利用Files#readAllLines来完成你想要的东西;不需要自己做任何迭代。你必须提供文件和字符集的路径(即Charset.forName("UTF-8");),但它的工作原理基本相同。

Path filePath = Paths.get("/path/to/file/on/system");
List<String> lines = Files.readAllLines(filePath, Charset.forName("UTF-8"));

1
投票

尝试像这样使用BufferedReader

static List<String> getFileLines(final String path) throws IOException {

    final List<String> lines = new ArrayList<>();

    try (final BufferedReader br = new BufferedReader(new FileReader(path))) {
        string line = null;
        while((line = br.readLine()) != null) {
            lines.add(line);
        }
    }

    return lines;
}
  • 为结果创建一个空列表。
  • BufferedReader上使用try-with-resources语句来安全地打开和关闭文件
  • 读取行直到BufferedReader返回null
  • 返回列表

1
投票

由于您想从特定文本文件中读取整行,我建议您使用BufferedReader类。

您可以像这样创建一个BufferedReader对象:

BufferedReader br = new BufferedReader(new FileReader(filenName));//fileName is a string
//that contains the name of the file if its in the same folder or else you must give the relative/absolute path to the file

然后使用BufferedReader对象上的readLine()函数读取文件的每一行。您可以尝试以下内容。

    try
    {
        //read each line of the file
        while((line = br.readLine()) != null)//if it reaches the end of the file rd will be null
        {
          //store the contents of the line into an ArrayList object
        }
    }catch(IOException ex)
    {
        System.out.println("Error");
    }

0
投票

你可能会用

final List<String> lines =
   Files.lines(Paths.get(path)).collect(Collectors.toList());

lines(Path, Charset)的变种。

© www.soinside.com 2019 - 2024. All rights reserved.