gpt4 book ai didi

java - BufferedWriter 不生成文件输出

转载 作者:行者123 更新时间:2023-12-01 12:22:41 27 4
gpt4 key购买 nike

在我的代码中,我必须采用从第二个单词开始的所有其他单词并将其反转。其他类/线程做得很好。我可以将输出打印到控制台窗口,并且打印正确。但是,每当我尝试写入桌面上的文本文件时,它不会产生任何输出。

我的代码:

package ProducerConsumerAssignment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.util.concurrent.BlockingQueue;

/**
*
* @author Tyler Weaver
*/
public class WordWriter implements Runnable {

private final String END_FLAG = "Terminate the queue";
private static BlockingQueue<CharSequence> in;
private final File output;

/**
* Constructs a WordWriter object
*
* @param file the file to write words to
* @param queue the blocking queue to retrieve words from
*/
public WordWriter(final File file, BlockingQueue queue) {
output = file;
in = queue;
}

/**
* Executes when being called in a thread
*/
@Override
public void run() {
boolean isInterrupted = false;

while (!isInterrupted) {
try (BufferedWriter out = new BufferedWriter(new FileWriter(output))) {
CharSequence word = in.take();

if (word.toString().equalsIgnoreCase(END_FLAG))
Thread.currentThread().interrupt();

out.write(word.toString() + " ");
System.out.printf("%s%n", word);
} catch (IOException ex) {
System.err.printf("Error closing the file!%n%s%n", ex);
} catch (InterruptedException ex) {
isInterrupted = true;
}
}
}
}

最佳答案

您将在每次迭代时关闭 BufferedWriter

您可以将 BufferedWriter 对象移出 while 循环,并在最后调用 BufferedWriter.close()

BufferedWriter writer = new BufferedWriter(new FileWriter(String));
while (true) {
CharSequence word = in.take();
if (word.toString().equalsIgnoreCase(END_FLAG)) {
break;
}
try {
writer.write(word + " ");
} catch (IOException io) {
break;
}
}
writer.close();

关于java - BufferedWriter 不生成文件输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26560548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com