有没有办法让FileWriter将文本文件中的第一行移动到底部?

时间:2018-04-03 23:50:06

标签: java file filereader java-io filewriter

我有一个文本文件,每次运行jar时都需要编辑。这是最初的样子。

1.png
2.png
3.png
4.png

我一直在尝试做的是使用FileWriter将顶行移到底部,所以下一行将位于顶部,结果就是。

2.png
3.png
4.png
1.png

这是我到目前为止编写的代码:

    BufferedReader reader = new BufferedReader(new FileReader("list.txt"));
    FileWriter writer = new FileWriter("list.txt");

    String newName = scan.nextLine();
    writer.write(newName);

    reader.close();
    writer.close();

这不会起作用,因为文中唯一的内容是png.2。所以我想知道...有没有办法告诉FileWriter或其他什么来简单地将第一行移到底部?

1 个答案:

答案 0 :(得分:0)

很高兴您找到了解决方案但是如果您想要其他解决方案,您可以尝试使用此方法代码。该方法允许您将任何文字文件行移动到文件中的任何文字行位置。

代码评论很好。阅读方法上方的文档:

/**
 * Moves a text file line supplied as a literal file line number to another literal 
 * file line location.<br><br>
 * 
 * A temporary file is created with the modifications done. The original file is then 
 * deleted and the modified temporary file is renamed to the same name that the original 
 * file held.<pre>
 * 
 * <b>Example Usage:</b>
 * 
 *    {@code 
 *      try {
 *          moveFileLine("list.txt", 3, 1);
 *      }
 *      catch (IOException ex) {
 *            Logger.getLogger(getName()).log(Level.SEVERE, null, ex);
 *      }
 *      }</pre>
 * 
 * @param filePath (String) The full path and file name of the text file to process.<br>
 * 
 * @param lineToMove (Integer - int) A literal file line number of the text you want 
 * to move. By literal we mean line 1 is considered the first line of the file (not 0).<br>
 * 
 * @param moveToLine (Optional - Integer - int - Default is 0) A literal file line 
 * number of where you want to move the file line text to. If 0 or nothing is is 
 * supplied then the line to move is placed at the end of the file otherwise the 
 * text is placed at the literal file line specified. By literal we mean line 1 is 
 * considered the first line of the file (not 0).<br><br>
 * 
 * If a value is supplied which is greater than the actual number of lines in file 
 * then that value is automatically changed to the number of lines in file which 
 * will therefore place the line-to-move to the end of file.<br>
 * 
 * @throws FileNotFoundException
 * @throws IOException
 */
@SuppressWarnings("null")
public void moveFileLine (String filePath, int lineToMove, int... moveToLine) 
        throws FileNotFoundException, IOException {
    int moveTo = 0; // Default move to
    // Acquire the optional move-to line number if supplied.
    if (moveToLine.length > 0) {
        moveTo = moveToLine[0];
    }

    // open a stream reader and writer.
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    FileWriter writer = new FileWriter("tmpMoveLineFile.txt");

    String line;  // The current file line text bing processed.
    String newLine = System.lineSeparator(); // System Line Separator.
    String moveLineString = ""; // Will hold the file line text to move.
    int lineCounter = 0; // Keeps track of the current file line.

    // Get and hold the file line contents we want to move.
    while ((line = reader.readLine()) != null) {
        lineCounter++;
        if (lineCounter == lineToMove) {
            moveLineString = line;
            if (moveTo > 0) { break; }
        }
    }
    // Close the reader (if it's open)
    if (reader != null) { reader.close(); }

    // If no Move-To line number was supplied then move the
    // desired line to end of file so as to be the last line.
    if (moveTo <= 0 || moveTo > lineCounter) {
        moveTo = lineCounter;
    }


    // Set up to start reading our file from the beginning again.
    reader = new BufferedReader(new FileReader(filePath));
    lineCounter = 0;  // Reset the line counter

    // Start reading in file data one line at a time
    while ((line = reader.readLine()) != null) {
        lineCounter++;// increament to keep track of the current line number

        // If the line counter equals the supplied line to move to then...
        if (lineCounter == moveTo) {
            // Ternary Operator is used here. If the current line counter
            // value is greater than 1 and the current line counter is
            // greater than the line to move then write the current line
            // the first then the line-to-move text otherwise write the
            // line-to-move first then write the current line.
            writer.write((lineCounter > 1 && lineCounter > lineToMove ? 
                    line + newLine + moveLineString + newLine : 
                    moveLineString + newLine + line + newLine));
        }
        // otherwise just write the encountered line.
        else if (lineCounter != lineToMove) {
            writer.write(line + newLine);
        }
    }
    // Close the reader and Writer.
    writer.close();
    reader.close();

    // delete the original file then Rename the newly created tmp 
    // file to the Original File name supplied.
    File origFile = new File(filePath);
    if (origFile.delete()) {
        File srcFile = new File("tmpMoveLineFile.txt");
        srcFile.renameTo(origFile);
    }
}