当前位置: 首页 > 知识库问答 >
问题:

为什么使用Writer后,我的文件中没有输出?[关闭]

伊裕
2023-03-14

我正在尝试制作一个程序,它可以生成时间表,并将一个数据输出到一个名为log的文件中。txt作为一个日志文件,但当我运行它时,它所做的只是运行时间表并生成文件,但不向文件写入任何内容。谁能告诉我,我的代码怎么了?如果你愿意,谢谢。

关键:

  • [.jar=runnable file]

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

Java博士:-http://wardogsk93-ftp.bugs3.com/Downloads/Java/Counter/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();
        }
    }
}

输出课程:-

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个答案

墨雨华
2023-03-14

当完成对文件的写入时,您必须始终使用clo()方法。否则它将不会保存它(您也希望关闭以避免资源泄漏错误...请阅读此处)。所以在这个方法中:

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();
        }
    }
}

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

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

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

致:

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

FileWriter中的第二个参数是确认是否要覆盖文件或追加到文件中。请查看此示例。

 类似资料:
  • 我正试图使用ProGuard混淆我的JAR文件。 明确地我有一个Java/Spring web应用程序。所以我制作了一个WAR文件。 我已将所有类从WAR文件的/WEB-INF/classes文件夹复制到一个新的JAR文件中。 我启动了ProGuard GUI,并选择了我的JAR文件作为输入。我指定了一个新的输出。JAR文件。我添加了所有的 /WEB-INF/lib/*. jar文件作为"库罐"。

  • 我正在尝试上传一个文件名和一个帖子(9插科打诨风格)到我的mysql数据库,并存储文件到我的项目文件夹。我正在从前端获取文件(前端的console.log工作得很完美),然后我使用nodejs+express后端处理文件并将其发送到我的数据库。我创建了一个multer中间件来设置文件名,扩展名,磁盘位置,然后在一个控制器中我试图得到文件发送它做数据库。console.log“route ok”可以

  • 我正在做一个任务,我必须创建一个“理想体重”计算器(有点像BMI计算器)。用户应该输入他们的身高、姓名和他们希望接收答案的测量系统。 IE;测量系统=(M)etric或(I)mperial,其中用户输入一个“M”或一个“I”。这意味着他们输入的高度必须对应于他们选择的单位。 IE;身高=1.5米或59英寸(除了他们不写单位,只写数字)。 我试图修复可能存在的任何语法错误,目前不再有任何错误,但当我

  • 我的目录上有一个文件。我只需要在我的超文本标记语言页面上的按钮为用户下载此文件。 我想出了这个代码,但问题是,当我单击在我的超文本标记语言页面没有发生任何事情,也没有错误。但是文件没有被下载。 我的密码在烧瓶里 注意:我检查了所有关于堆栈溢出的问题。他们中的大多数人在下载之前把文件放在静态文件夹中,或者其他我不理解他们在做什么的人,因为他们没有在HTML部分显示要做什么

  • 我包一个插座。通过InputStreamReader获取getInputStream(),并包装一个套接字。getOutputStream()由OutputStreamWriter创建。我发现这些流的关闭顺序真的很重要,但我不知道为什么。 如果我先关闭outputStream,然后再关闭inputStream,它可以正常工作: 但是,如果我先关闭inputStream,然后再关闭outputStr