saum
saum

Reputation: 343

Java,writing console content to file

I am testing, trying to write the console content to file but when I run the app I the text file that was generated is empty. I want the user to enter some details when the user finished entering the details. I'd like the user to enter the filename to write the console content to. However, the file that was generated is empty.

public void test() {
    boolean check=true;
    int i=0;
    for (i=0;i<5;i++) {
        System.out.println("Enter your name");
        String name=Keyboard.readInput();
        System.out.println("Name:"+ name);
        System.out.println("Enter your age");
        int age=Integer.parseInt(Keyboard.readInput());
        System.out.println("Age:"+age);
    }

    out.println("enter 1 to save to file");
    int num=Integer.parseInt(Keyboard.readInput());
    if (num == 1) {
        out.println("Enter the file name to write to:\n");
        String filename = Keyboard.readInput();
        File myfile = new File(filename);

        try {
                PrintStream out = new PrintStream(new FileOutputStream(myfile));
                System.setOut(out);
        } catch (IOException e) {
            out.println("Error:" + e.getMessage());
        }
    }
}

Upvotes: 1

Views: 80

Answers (2)

Joe
Joe

Reputation: 1342

Java 8+

static void writeFile(String path, String...lines) throws IOException {
    Files.write(
        Paths.get(path), 
        Arrays.asList(lines));
}

Upvotes: 0

Khalid Shah
Khalid Shah

Reputation: 3232

You only create the file and not write anything on the file that's why file is empty. After Creating a file you have to write something on the file via PrintStream.println() method.

try {
    PrintStream out = new PrintStream(new FileOutputStream(myfile));
    out.println("some text"); // it will write on File

    // OR if you setOut(PrintSrtream) then
    System.setOut(out);
    System.out.println("some text");// this will also write on file
} catch (IOException e) {
    out.println("Error:" + e.getMessage());
}

Upvotes: 2

Related Questions