代码之家  ›  专栏  ›  技术社区  ›  Meowminator

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

  •  0
  • Meowminator  · 技术社区  · 6 年前

    我有一个文本文件,需要在每次运行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 回复  |  直到 6 年前
        1
  •  0
  •   DevilsHnd - 退した    6 年前

    很高兴您找到了一个解决方案,但如果您需要另一个解决方案,可以尝试此方法代码。该方法允许您将任何文本文件行移动到文件中的任何文本行位置。

    代码注释得很好。阅读方法上方的文档:

    /**
     * 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);
        }
    }