Since I assume you are a beginner in Java, i wrote a short code sample with self-explanatory comments. The application runs on the command line and reads line by line, where a line ends by hitting the enter key. If you type “EXIT”, the application quits. The text file to be written is located at C:\Folder\Text.txt
.
This is a very basic example, so just extend it to your needs. For better platform independence, you can substitute the hardcoded \\
slash by File.separator
. As a note to the finally block: In newer versions of Java (>= 7), you can save a lot of boilerplate code by using the try-with
syntax. Read more about it here, if you are interested.
You can inform yourself about the basic I/O mechanisms in the tutorial here.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
// The reader and writer objects must be declared BEFORE
// the try block, otherwise they are not 'visible' to close
// in the finally block
Scanner reader = null;
FileWriter writer = null;
String inputText;
try {
// Reader and writer are instantiated within the try block,
// because they can already throw an IOException
reader = new Scanner(System.in);
// Do not forget, '\\' is the escape sequence for a backslash
writer = new FileWriter("C:\\Folder\\Text.txt");
// We read line by line, a line ends with a newline character
// (in Java a '\n') and then we write it into the file
while (true) {
inputText = reader.nextLine();
// If you type 'EXIT', the application quits
if (inputText.equals("EXIT")) {
break;
}
writer.write(inputText);
// Add the newline character, because it is cut off by
// the reader, when reading a whole line
writer.write("\n");
}
} catch (IOException e) {
// This exception may occur while reading or writing a line
System.out.println("A fatal exception occurred!");
} finally {
// The finally branch is ALWAYS executed after the try
// or potential catch block execution
if (reader != null) {
reader.close();
}
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
// This second catch block is a clumsy notation we need in Java,
// because the 'close()' call can itself throw an IOException.
System.out.println("Closing was not successful.");
}
}
}
}