Move first line of .txt file add to last line

1.4k views Asked by At

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

  1. Find "text" from input file and output to a temp file. (I could set "text" to a string buffRead.readLine ??) and then...
  2. 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.

2

There are 2 answers

0
CAD97 On

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.

0
Sanjit Kumar Mishra On
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();

This will return the first line of text from the file and discard it because you don't store it anywhere. To overwrite your existing file:

FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
    String next = fileScanner.nextLine();
    if(next.equals("\n") out.newLine();
    else out.write(next);
    out.newLine();   
}
out.close();

Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.

Add the same line to the last line of this file have a look into this link https://stackoverflow.com/a/37674446/6160431