首页 > 解决方案 > 在我调用我的 IO 方法后没有生成文件

问题描述

`公共抽象类 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.txt 的日志文件。然后我有另一台电视 (LG),它也需要有自己的日志文件。我是否需要编写两个单独的 if 语句来确定电视的品牌,然后将其指向它自己的日志文件?

标签: javafileinputmethodsio

解决方案


问题在于同时在同一个文件上使用读取器和写入器。一旦我摆脱了打开文件的代码,该方法就可以正常工作。我编辑了代码以反映正确的更改。

我猜想同时在同一个文件上使用读取器和写入器会出现问题。我建议您消除阅读器并打开文件进行追加。或者,您可以为编写器打开一个不同的文件,然后在完成写入后,删除原始文件并重命名您的新文件。– bcr666 6 分钟前


推荐阅读