0

Hi guys, could anyone tell me why my code cannot input contents into the file, thanks in advance.

import java.io.*;
import java.util.Scanner;

public class FileIO {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// public void writeToFile(){
		try {
			
			File outFile = new File(args[0] + ".txt");
			PrintWriter out = new PrintWriter(outFile);
			Scanner input = new Scanner(System.in);
			System.out.print("Input the content save to the file: ");
			
			while (input.hasNext()) {
				out.print(input.next());
				out.println();
			}
			out.close();
			System.out.println("input to file successfully");
		} catch (FileNotFoundException e) {
			System.out.println("The file not found.");
		}
	}
}
3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by freelancelote
0

The API documentation for the constructor your using says:

Creates a new PrintWriter, without automatic line flushing

The close() method should flush the stream before closing the file, but try calling flush before calling close.

0

Thanks masijade, but as I am new in java, could you explain more details to me. I know I need stop the while loop to achieve my goal, but I donot know how. Thanks in advance.

0

newjavastudent,
as it's coded, you just have to break your while loop with ctrl+c while the program is running and once you've finished writing whatever you'd like on the new generated file.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.