如何通过Files.list()方法获取文本文件的行字符串数组(强制使用该方法)
Solution to Read File Lines Using
Files.list Got it, let's break down how to fix this. The core issue with your current code is that Files.list(Paths.get("path")) returns a stream of Path objects representing every entry in the directory—not the content of your text file. That's why toArray() gives you an array of file paths instead of the lines from your target file.
Here's how to adjust your code while still adhering to the requirement of using Files.list:
Key Steps to Implement
- Filter the directory stream to locate your specific text file
- Read all lines from the found file
- Convert lines to a String array (type-safe instead of Object[])
- Properly close the stream (using try-with-resources to avoid resource leaks)
Corrected Code
// Assuming 'path' is a class-level String variable pointing to your directory public String[] returnStrings(String targetTxtFile) { try (Stream<Path> directoryStream = Files.list(Paths.get(path))) { // Find the target text file in the directory stream Path targetFile = directoryStream .filter(p -> p.getFileName().toString().equals(targetTxtFile)) .findFirst() .orElse(null); if (targetFile != null) { // Read all lines and convert to a String array List<String> fileLines = Files.readAllLines(targetFile); return fileLines.toArray(new String[0]); } } catch (IOException ex) { // Handle exceptions like missing directory, permission issues, or file read errors ex.printStackTrace(); } // Return null if file not found or an error occurred return null; }
Explanation of Key Parts
try (Stream<Path> ...): This try-with-resources statement ensures the directory stream is closed automatically, which is mandatory forFiles.listto release underlying system resources.filter(...): Narrows down the stream to only the Path matching your target filename (replacetargetTxtFilewith your actual filename, e.g.,"data.txt").findFirst(): Retrieves the first matching Path (assuming only one file with that name exists in the directory). If no match is found, it returnsnull.Files.readAllLines(targetFile): Reads all lines from the found file into aList<String>, which we then convert to a String array usingtoArray(new String[0]).
Usage Example
To get lines from your text file, call the method like this:
String[] lines = returnStrings("your-file.txt");
内容的提问来源于stack exchange,提问作者miclelov
相关产品推荐
相关产品推荐

