简体   繁体   中英

java read files from directory iteratively and assign values separate arraylists

I read txt files iteratively and what i want to do is read the contents of each file and assign the content to the arraylists separately. The code that i use for reaching the txt files :

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();
}

I'm not sure I understood the question.

Use a BufferedReader to read the contents of the files line by line, there you can add the lines to the 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();
  }

If you are using Java 7, you can use the method Files.readAllLines(path, characterSet) like
List lines = Files.readAllLines(path, 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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM