[英]File is not being made after I call my IO method
`公共抽象类 TV 实现了 Logger {
protected int currentChannel;
protected int currentVolume;
protected String model;
public TV(String model)
{
this.model = model;
currentChannel = 2;
currentVolume = 10;
}
public void incChannel()
{
getcurrentChannel();
currentChannel = currentChannel + 1;
writeToLogFile("Increasing channel to " + currentChannel);
System.out.println("Increasing channel to " + currentChannel);
}
public void decChannel()
{
getcurrentChannel();
currentChannel = currentChannel - 1;
writeToLogFile("Decreasing channel to " + currentChannel);
System.out.println("Decreasing channel to " + currentChannel);
}
public void incVolume()
{
getcurrentVolume();
currentVolume = currentVolume + 1;
writeToLogFile("Increasing volume to " + currentVolume);
System.out.println("Increasing volume to " + currentVolume);
}
public void decVolume()
{
getcurrentVolume();
currentVolume = currentVolume - 1;
writeToLogFile("Decreasing volume to " + currentVolume);
System.out.println("Decreasing volume to " + currentVolume);
}
public void changeChannel(int currentChannel)
{
this.currentChannel = currentChannel;
writeToLogFile("Changing channel to " + currentChannel);
System.out.println("Changing channel to " + currentChannel);
}
public void writeToLogFile(String message)
{
model = getModel();
try {
FileReader fr = new FileReader(new File("./model.txt"));
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(new File("./model.txt"), true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String line = br.readLine();
while (line != null) {
Scanner scanLine = new Scanner(line);
String mess = scanLine.next();
pw.println(message);
pw.println(mess);
line = br.readLine();
}
br.close();
pw.flush();
pw.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
}
catch (IOException e)
{
System.out.println("An IO error occurred.");
}
}`
当我调用运行我的程序时,我的 writeToLogFile 方法无法正常工作。 当它被调用时,它没有根据需要制作文本文件。 我需要 writeToLogFile 方法来创建文件,然后在其他方法中调用它时附加它。 另外,我在这个节目中有两种型号的电视。 当我使用其中一台电视 (Sony) 时,我希望它写入自己的名为 Sony.txt 的日志文件。 然后我有另一台电视(LG)也需要有自己的日志文件。 我是否需要编写两个单独的 if 语句来确定电视的品牌,然后将其指向自己的日志文件?
问题在于同时在同一个文件上使用读取器和写入器。 一旦我摆脱了打开文件的代码,该方法就可以正常工作。 我编辑了代码以反映正确的更改。
我猜想在同一文件上同时使用读取器和写入器会出现问题。 我建议您消除阅读器并打开文件进行追加。 或者,您可以为作者打开一个不同的文件,然后在完成写入后,删除原始文件并重命名新文件。 – bcr666 6 分钟前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.