java迭代地从目录中读取文件,并为单独的数组列表赋值



我反复读取txt文件,我想做的是读取每个文件的内容,并将内容分别分配给数组列表。我用来访问txt文件的代码:

Path basePath = Paths.get("filepath");
 try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath,
    "*.txt")) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }
} catch (IOException e) {
  e.printStackTrace();
}

我不确定我是否理解这个问题。

使用BufferedReader逐行读取文件的内容,在那里您可以将行添加到ArrayLists。

 Path basePath = Paths.get("filepath");
 try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath,
    "*.txt")) {
  for (Path path : pathList) {
    BufferReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
    String currentLine = reader.readline();
    ArrayList<String> comments = new ArrayList<>();
    while( currentLine != null ) {
        comments.add(currentLine);
        currentLine = reader.readline();
    }
  }
  } catch (IOException e) {    
    e.printStackTrace();
  }

如果您使用的是Java 7,您可以使用方法Files.readAllLines(路径,characterSet),如
列表行=Files.readAllLines(路径,Charset.defaultCharset());

public class FileToArrayLists {
    public static void main(String[] args) {
        Path basePath = Paths.get("C:\temp");
        try (DirectoryStream<Path> pathList = Files.newDirectoryStream(
                basePath, "*.txt")) {
            Map<String, List<String>> fileLists = new HashMap<>();
            for (Path path : pathList) {
                fileLists.put(path.toString(), Files.readAllLines(path, Charset.defaultCharset()));
            }
            System.out.println(fileLists);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新