在java中,如何删除文件中的一行,使行下的内容紧跟行上的内容?

在java中,如何删除文件中的一行,使行下的内容紧跟行上的内容?,java,Java,我有如何删除文件中某行的代码,但在执行删除操作后,文件中有一个新的空行,用于分隔删除行上方的内容和下方的内容 try { List<String> line = Files.readAllLines(path,StandardCharsets.ISO_8859_1); for (int i = 0; i < line.size(); i++) { if (dataStoreLines.get(i)

我有如何删除文件中某行的代码,但在执行删除操作后,文件中有一个新的空行,用于分隔删除行上方的内容和下方的内容

try {

            List<String> line = Files.readAllLines(path,StandardCharsets.ISO_8859_1);
            for (int i = 0; i < line.size(); i++) {
                if (dataStoreLines.get(i).contains(key)) {
                    dataStoreLines.set(i, "");
                    break;
                }
            }
如果我想删除第2行

用我的代码修改的文件如下

Line 1

Line 3
中间的空行没有被删除

两件事:

  • 您没有“删除一行”的代码,您有将该行变成空字符串的代码

  • 代码showb不是在文件上运行,而是在内存中从文件初始化的列表上运行

  • 您需要编写代码来

    a) 从列表中删除条目

    b) 将结果列表写入文件

    public static void removeLineInFile(Path src, int excludeLineNumber) throws IOException {
        Path dest = createTemporaryFile(src);
        copyContent(src, dest, excludeLineNumber);
        Files.delete(src);
        Files.move(dest, src);
    }
    
    private static Path createTemporaryFile(Path src) throws IOException {
        return Files.createFile(Paths.get(src.toString() + ".tmp"));
    }
    
    private static void copyContent(Path src, Path dest, int excludeLineNumber) throws IOException {
        try (BufferedReader in = new BufferedReader(new FileReader(src.toString()));
             BufferedWriter out = new BufferedWriter(new FileWriter(dest.toString()))) {
            int i = 0;
            String line;
    
            while ((line = in.readLine()) != null) {
                if (i++ != excludeLineNumber) {
                    out.write(line);
                    out.newLine();
                }
            }
        }
    }
    
    演示:

    public static void main(String... args) throws IOException {
        Path src = Path.of("e:/lines.txt");
        removeLineInFile(src, 1);
    }
    
    line0
    line1
    line2
    line3
    
    line0
    line2
    line3
    
    之前:

    public static void main(String... args) throws IOException {
        Path src = Path.of("e:/lines.txt");
        removeLineInFile(src, 1);
    }
    
    line0
    line1
    line2
    line3
    
    line0
    line2
    line3
    
    之后:

    public static void main(String... args) throws IOException {
        Path src = Path.of("e:/lines.txt");
        removeLineInFile(src, 1);
    }
    
    line0
    line1
    line2
    line3
    
    line0
    line2
    line3
    

    与其将当前列表元素设置为空字符串,不如将其从列表中删除。谢谢@Aaron,效果很好。不客气,很高兴您的问题得到解决。我想您感谢了错误的人提供的代码@oleg.cherednik提供的,不是我。谢谢@oleg.cherednik,我需要通过将文件中的行(字符串)作为参数来删除文件中的一行,因为行号不会提供,但这段代码看起来很棒!