为什么使用Writer后我的文件中没有输出?

时间:2014-01-30 14:45:16

标签: java file io

我正在尝试创建一个执行时间表的程序,并将其输出到名为log.txt的文件作为日志文件,但是当我运行它时它所做的只是运行并执行时间表和制作文件,但不向文件写入任何内容。有人可以告诉我,我的代码有什么问题吗?如果你这样做,谢谢。

键:

  • [.jar = runnable file]
  • [.zip =源代码]

下载链接: - http://wardogsk93-ftp.bugs3.com/Downloads/Java/Counter/

Java Doc: - http://wardogsk93-ftp.bugs3.com/Downloads/Java/Counter/Java%20Doc/

Main.java: -

public class Main {

    /************************************************/
    /*************STUFF YOU CAN CHANGE***************/
    /************************************************/

    /** change this to start at a different number must be a number {@link Integer}**/
    public static int minCount = 1; 

    /** change to change the number of where the programme will end must be a number {@link Integer}**/
    public static int maxCount = 10;

    /** change this to how many times you want to sleep for in seconds (1 = 1 second, 2 = 2 second, 10 = 10 second) before moving to next sum must be a number {@link Integer} **/
    public static int sleepAmountMultiplyer = 1; 

    /** true = outputs to the command prompt / false = outputs to eclipse console {@link boolean}**/
    public static boolean outputTOCMD = true; 

    /************************************************/
    /******DONT CHANGE ANYTHING BELOW THIS LINE******/
    /************************************************/

    /** allows to output to a command prompt **/
    private static Console cmd;
    private static Output file;

    private static int endNumber = maxCount + 1;
    private static int sleepAmount = 1000 * sleepAmountMultiplyer;

    /**
     * main method
     * call this to start
     **/    
    public static void start() {
        file = new Output();

        if (outputTOCMD) {

            cmd = new Console();

            count();

            cmd.exit();
        } else {
            count();

            System.exit(1);         
        }
    }

    public static Main getInstance() {
        return Main.getInstance();
    }

    /**code to start running**/
    private static void count() { 
        try {
            for (int i = minCount; i < maxCount + 1; i++) {
                int j = i * i;

                Thread.sleep(sleepAmount);

                if (i == endNumber) {
                    return;
                }

                if (outputTOCMD) {
                    cmd.out(i + " X " + i + " = " + j);

                    file.write(String.valueOf(i) + " X " + String.valueOf(i) + " = " + String.valueOf(j));
                } else {
                    System.out.println(i + " X " + i + " = " + j);

                    file.write(String.valueOf(i) + " X " + String.valueOf(i) + " = " + String.valueOf(j));
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output.class: -

import java.io.*;

public class Output {
    public Output() {}

    private Console cmd;
    private File logFile;
    private String input;
    private BufferedReader reader;
    private BufferedWriter writer;

    public Output(Console cmd, File logFile, BufferedReader reader, BufferedWriter writer) {
        this.cmd = cmd;
        this.logFile = logFile;
        this.reader = reader;
        this.writer = writer;
    }

    /** writes to a log file using {@link FileWriter} **/
    public void write(String message) {
        try {
            logFile = new File("log.txt");
            writer = new BufferedWriter(new FileWriter(logFile));

            if (!logFile.exists()) {
                writer.write(message);
                writer.close();
            } else {
                read();
                 if (logFile.isFile()) {
                     logFile.delete();

                     writer.write(message);
                 }
            }
        } catch (IOException e) {
            if (Main.outputTOCMD) {
                cmd.out(e.getMessage());
            } else {
                e.printStackTrace();
            }
        }
    }

    /** writes to a log file using {@link FileReader} **/
    public void read() {
        try {           
            logFile = new File("log.txt");
            reader = new BufferedReader(new FileReader(logFile));

            if (logFile.exists()) {
                setInput(reader.readLine());
            }
        } catch (IOException e) {
            if (Main.outputTOCMD) {
                cmd.out(e.getMessage());
            } else {
                e.printStackTrace();
            }
        }
    }

    /**
     * @return the input
     */
    private String getInput() {
        return input;
    }

    /**
     * @param input the input to set
     */
    private String setInput(String input) {
        this.input = input;
        return input;
    }
}

Console.class: -

import java.awt.Color;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;

/**
 * Creates the command prompt window in class {@link Console}
 */
public class Console {
    private JFrame frame;
    private JTextArea console;
    private Image icon;

    public Console() {
        try {
            frame = new JFrame();
            frame.setBackground(Color.BLACK);
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setName("Commad Prompt");
            frame.setSize(678, 340);
            frame.setTitle(frame.getName());
            frame.setVisible(true);

            icon = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/en/e/ef/Command_prompt_icon_(windows).png")).getImage();
            frame.setIconImage(icon);

            console = new JTextArea();
            console.setAutoscrolls(true);
            console.setBackground(Color.BLACK);
            console.setEditable(false);
            console.setForeground(Color.WHITE);
            console.setSelectionColor(Color.WHITE);
            console.setSelectedTextColor(Color.BLACK);
            console.setVisible(true);

            frame.add(console);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param {@link String} text does the same as {@link System}.out.println();
     */
    public void out(String text) {
        console.append(text + "\n");
    }

    /**
     * @exception {@link Exception} to catch any errors and prints them to the window
     * does the same has {@link System}.exit(1);
     */
    public void exit() {
        try {
            Thread.sleep(1000 * Main.sleepAmountMultiplyer);

            console.disable();
            frame.dispose();
            System.exit(1);
        } catch (Exception e) {
            this.out(e.getMessage());
        }
    }

    /**
     * @return Allows you to acces all the stuff in <br>{@link Console}</br>
    **/
    public Console getInstance() {
        return this;
    }
}


Launch File:-


public class Test {
    public static void main(String[] args) {
        Main.minCount = 1;
        Main.maxCount = 10;
        Main.sleepAmountMultiplyer = 1;
        Main.outputTOCMD = true;

        Main.start();
    }
}

1 个答案:

答案 0 :(得分:2)

完成写入文件后,必须始终使用close()方法。否则它不会保存它(you also want to close to avoid resource leak errors...read here)。所以在这个方法中:

public void write(String message) {
    try {
        logFile = new File("log.txt");
        writer = new BufferedWriter(new FileWriter(logFile));

        if (!logFile.exists()) {
            writer.write(message);
            writer.close();
        } else {
            read();
             if (logFile.isFile()) {
                 logFile.delete();

                 writer.write(message);
             }
        }
        //close the buffer writer in order to save
        writer.close();
    } catch (IOException e) {
        if (Main.outputTOCMD) {
            cmd.out(e.getMessage());
        } else {
            e.printStackTrace();
        }
    }
}

或者,您可以在finally块中关闭。阅读完毕后,您还必须关闭BufferReader。如果您计划对同一文件进行多次Thread读/写,则在使用Thread时需要非常小心。

注意:每次都会覆盖该文件。但是,如果您想 追加 数据,请更改此行:

writer = new BufferedWriter(new FileWriter(logFile));

要:

writer = new BufferedWriter(new FileWriter(logFile, true));

FileWriter中的第二个参数确认您是要覆盖文件还是附加到文件。看看这个example