Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

How to delete a line in a file such that the contents below the line should follow the contents above the line immediately in java?

I have the code for how to delete a line in a file but after the delete operation is performed there is a new blank line in the file which is separating the content above the deleted line and the content below it.

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;
                }
            }

Suppose the file contains

Line 1
Line 2
Line 3

if I want to delete Line 2

The modified file with my code is like

Line 1

Line 3

The empty line in between is not getting deleted


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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();
            }
        }
    }
}

Demo:

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

Before:

line0
line1
line2
line3

After:

line0
line2
line3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...