-4

I'm trying to make a programme which does times tables and it outputs a to a file called log.txt as a log file, but when I run it all it does is runs though and does the times tables and makes the file, but writes nothing to the file. Can someone please tell me, what's wrong with my code? If you do, thanks.

Key:

  • [.jar = runnable file]
  • [.zip = source code]

Download links:- 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();
    }
}
Kevin Panko
  • 8,356
  • 19
  • 50
  • 61

1 Answers1

2

You must always use the close() method when finished writing to a file. Else wise it won't save it (you also want to close to avoid resource leak errors...read here). So in this method:

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

Alternatively, you can close in a finally block. You must also close the BufferReader after you're done reading. You need to be very careful when using Thread if you plan to have multiple Thread reading/writing to same file.

NOTE: This will overwrite the file each time. However, if you want to append the data, change this line:

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

To:

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

The second parameter in FileWriter is confirming whether you want to overwrite the file or append to the file. Check out this example.

Community
  • 1
  • 1