I have a.txt
list trying to move the first line to the last line in Java
I've found scripts to do the following
- Find "text" from input file and output to a temp file. (I could set "text" to a string buffRead.readLine ??) and then...
- delete the orig file and rename the new file to the orig?
Please for give me I am new to Java but I have done a lot of research and can't find a solution for what I thought would be a simple script.
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.
This gives you an easy way to read the contents of the file
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 aPrintWriter
, 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.
This saves the first line of the file to
text
.While
reader
has text remaining in it, print the lines into thewriter
.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.
Alternatively, you could also wrap the entire thing in a try-with-resources to perform the same cleanup automatically.