从文件中读取随机行并将其写入另一个文件

时间:2015-10-21 22:17:58

标签: java

BufferedWriter不会写入文件“segfil.txt”:

public static String fileSeg(String name, int co) throws IOException {
    String randomString = "";
    File fil5 = new File("segfil.txt");
    Random r;
    System.out.println("Dude what??");
    BufferedReader reader = new BufferedReader(new FileReader(name));
    BufferedWriter bfwt = newBufferedWriter(newFileWriter(fil5.getName()));
    List<String> lines = new ArrayList<String>();
    String line = reader.readLine();
    System.out.println(line);
    System.out.println("++++++++");
    bfwt.write(line);
    while (line != null) {
        lines.add(line);
        line = reader.readLine();
    }
    // Choose a random one from the list
    while (co > 0) {
        r = new Random();
        randomString = lines.get(r.nextInt(lines.size()));
        System.out.println(randomString);
        bfwt.write(randomString);
        System.out.println(co);
        co--;
    }
    return fil5.getName();
}

我已生成随机行但无法写入其他文件。该文件保持空白,因为它没有被写入。

3 个答案:

答案 0 :(得分:1)

你应该使用try-with-resources自动关闭文件(因此在Writer的情况下刷新):

try (BufferedReader reader = new BufferedReader(new FileReader(name));
     BufferedWriter bfwt = newBufferedWriter(newFileWriter(fil5.getName()))) {
  // Code using reader and bfwt.
}

答案 1 :(得分:0)

你写完后是否尝试冲洗?

bfwt.write(randomString);
bfwt.flush();

或者你有任何错误吗?

答案 2 :(得分:0)

您不会关闭资源/流。您需要从代码中改进资源管理。使用try-with-resources statement

List<String> lines = new ArrayList<>();
try (
  FileReader     fileReader     = new FileReader("...");
  BufferedReader bufferedReader = new BufferedReader(fileReader);
) {
   String line;
   while ( (line = bufferedReader.readLine()) != null) lines.add(line);
}

您还可以依赖PathStream API:

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

相同的逻辑适用于写:

Random random = ThreadLocalRandom.current();    
try (FileWriter fileWriter = new FileWriter("...")) {
  for (int i = 0; i < co; i++) {
    int lineNumber = random.nextInt(lines.size());
    String line = lines.get(lineNumber);
    fileWriter.write(line);
    fileWriter.write('\n');
  }
}

使用PathStream API:

Files.write(
  Paths.get("..."),
  ThreadLocalRandom.current()
    .ints(co, 0, lines.size())
    .mapToObj(lineNumber -> lines.get(lineNumber))
    .collect(Collectors.toList())
);