Because this is Java and concerns file IO, this is a non-trivial setup. The algorithm itself is simple, but the symbols required to do so are not immediately evident.
BufferedReader reader = new BufferedReader(new FileReader("fileName"));
This gives you an easy way to read the contents of the file fileName
.
PrintWriter writer = new PrintWriter(new FileWriter("fileName"));
This gives you a simple way to write to the file. The API to do so is the exact same as System.out
when you use a PrintWriter
, thus my choice to use one here.
At this point its a simple matter of reading the file and echoing it back in the correct order.
String text = reader.readLine();
This saves the first line of the file to text
.
while (reader.ready()) {
writer.println(reader.readLine());
}
While reader
has text remaining in it, print the lines into the writer
.
writer.println(text);
Print the line that you saved at the start.
Note that if your program does anything else (and it's just a good habit anyway), you want to close your IO streams to avoid leaking resources.
reader.close();
writer.close();
Alternatively, you could also wrap the entire thing in a try-with-resources to perform the same cleanup automatically.