将线放在先前的位置

时间:2015-06-06 20:52:38

标签: java

我想在新文本文档中的此行Min:30后面的文本文档中找到此行Min:15stop mon-fri后尝试执行以下操作,或者如果它可能在同一文本文档中,然后删除找到Min:行的空换行符。对于当前状态,线路正在被更改,而不是如结果那样简单。我该如何解决?

我感谢任何帮助。

简单:

4
stop mon-fri
Chinese 
death Radbruch-Platz 
operator 
Min:30
apologized 
cooperate 
4
stop mon-fri
government computers 
WASHINGTON 
suspected 
Min:15
Chinese 
hackers  

结果应如下所示

4
stop mon-fri
Min:30
dominant 2
death Radbruch-Platz 
operator 
apologized 
cooperate 
4
stop mon-fri
Min:15
government computers
WASHINGTON 
suspected 
Chinese 
hackers 

代码:

try (PrintWriter writer = new PrintWriter(path + File.separator + newName);
     Scanner scanner = new Scanner(file)) {

    ArrayList<String> store = new ArrayList<String>();
    int indexA = 0, indexB = 0;

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        store.add(line);
        if (line.startsWith("stop")) {
            indexA = store.size() ;
        } else if (line.startsWith("Min:")) {
            indexB = store.size() - 1;
            Collections.swap(store, indexA, indexB);
        }
    }
    for (String element : store) {
        writer.println(element);
    }
    scanner.close();
} catch (Exception e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:2)

由于您正在阅读整个文件,只是为了在执行修改后将其写回来,我只需使用Files.readAllLines()将所有信息转换为List<String>而非{{{} 1}}。

Scanner中获得数据之后,只需遍历它就可以应用相同的条件检查来查找您感兴趣的行的索引。

获得索引后,我会使用List<String>提供Collections.swap()而不是使用.set(),只需执行删除即可删除您不希望保留的行数据

完成修改List<String>后,您可以List<String>将其写回同一文件。

代码示例:

Files.write()

结果(来自显示):

public static void main(String[] args) throws Exception {
    List<String> myFileLines = Files.readAllLines(Paths.get("MyFile.txt"));

    // Printing the file before modifications for test purposes
    System.out.println("Before:");
    myFileLines.stream().forEach(line -> System.out.println(line));

    int stopMonFriIndex = -1;
    int minIndex = -1;
    for (int i = 0; i < myFileLines.size(); i++) {
        if (myFileLines.get(i).startsWith("stop")) {
            stopMonFriIndex = i;
        } else if (myFileLines.get(i).startsWith("Min:")) {
            minIndex = i;
        } else if (stopMonFriIndex > -1 && minIndex > -1) {
            // Set the Min: line after the stop line
            myFileLines.set(stopMonFriIndex + 1, myFileLines.get(minIndex));
            // Remove the Min: line
            myFileLines.remove(minIndex);
            // Reset indexes
            stopMonFriIndex = -1;
            minIndex = -1;
        }
    }

    // Print the file after modifications for test purposes
    System.out.println("\r\nAfter:");
    myFileLines.stream().forEach(line -> System.out.println(line));

    // Write the data back to the same file
    Files.write(Paths.get("MyFile.txt"), myFileLines);
}