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.");
		}
	}
}

Recommended Answers

All 3 Replies

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.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.