繁体   English   中英

从文本文件中删除特定行

[英]Delete specific line from text file

我想要一个方法来获取文件路径,然后从文本文件中删除特定行,这就是我想出的代码。

方法.java

public class Method {
static void deletefileline(String file, Integer line) throws IOException {
    ArrayList<String> filecontent = new ArrayList<String>();
    try {
        File myObj = new File(file);
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            filecontent.add(data);
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
    File f = new File(file);
    f.delete();
    filecontent.remove(line);
    try {
        File newfile = new File(file);
        newfile.createNewFile();
    } catch (IOException e) {
        System.out.println("An Error Occured");
    }
    for (Integer i = 0; i < filecontent.size(); i++) {
        String textToAppend = "\r\n" + filecontent.get(i);
        Path path = Paths.get(file);
        Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND);
    }
}

public static void main(String[] args) {
    deletefileline("src/test.txt", 1);
 }
}

这是文本文件

测试.txt

hi
hello
hii
helloo

这是我运行 Methods.java 后的文本文件

Output:

hi
hello
hii
helloo

它不会显示它,但在第一个“hi”之前有一个空格,所以它只在第 1 行添加了一个空格。

所以问题是,当它运行时,它只在第 1 行添加了额外的一行。

为什么不删除该行?

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

  • E remove(int index)删除此列表中指定 position 处的元素。
  • boolean remove(Object o)从此列表中移除第一次出现的指定元素(如果存在)。

由于Integer lineObject而不是原始数据类型int ,此调用

filecontent.remove(line);

尝试删除内容等于new Integer(1)的行。

将方法参数更改为int line或将类型转换添加到调用filecontent.remove((int) line)

为什么要添加一个空行?

此语句添加了额外的空间:

String textToAppend = "\r\n" + filecontent.get(i);

像这样改变它:

String textToAppend = filecontent.get(i) + "\r\n";

这是执行问题中提到的相同 function 的一个小片段(kotlin 版本,但同样可以在 java 中完成)

import java.io.File
class RemoveFileContent {
    fun deleteContentAtIndex(filePath: String, indexPos: Int) {
        val bufferedWriter = File("/SampleOutputFile.txt").bufferedWriter()
        File(filePath).readLines().filterIndexed { i, _ -> i != indexPos }.forEach {
            bufferedWriter.appendLine(it)
        }
        bufferedWriter.flush()
    }
}
fun main(args : Array<String>) {
    RemoveFileContent().deleteContentAtIndex("/SampleFile.txt",2)
}

Input :             Output:
    hi                  hi
    hello               hello
    hii                 helloo
    helloo

免责声明:请注意,如果您的文件内容很大,这可能会导致 memory 的高消耗,如此处所述 - 如何删除 java 中的文本文件的第一行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM