我想要一个方法来获取文件路径,然后从文本文件中删除特定的行,这就是我想出的代码。
方法.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 后的文本文件
输出:
hi
hello
hii
helloo
它不会显示它,但在第一个“hi”之前有一个空格,所以它只在第 1 行添加了一个空格。
所以问题是,当它运行时,它只在第 1 行添加了一个额外的行。
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
E remove(int index)
移除此列表中指定位置的元素。boolean remove(Object o)
从此列表中删除第一次出现的指定元素(如果存在)。
由于Integer line
isObject
而不是原始数据类型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";
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句