中易网

JAVA如何删除文本文档里的某一行

答案:4  悬赏:0  
解决时间 2021-01-12 01:13
  • 提问者网友:刺鸟
  • 2021-01-11 06:04
JAVA如何删除文本文档里的某一行
最佳答案
  • 二级知识专家网友:玩家
  • 2021-01-11 06:32
你可以用StreamReader一行一行地读,直到读完,你把读到的每一行加到ArrayList对象中存放,然后遍历这个ArrayList对象,对每一行进行判断处理,不要的直接删除,然后再用StreamWriter把ArrayList对象中的数据重写到文件中,原来的文件覆盖掉。
追问:求代码,新人,不太懂
追答:求采纳。。
全部回答
  • 1楼网友:执傲
  • 2021-01-11 09:19
我暂时保留我的看法!
  • 2楼网友:刀戟声无边
  • 2021-01-11 08:23
import java.io.*;
public class Test {
public static void delete(String file, String text) {
delete(new File(file), text);
}
public static void delete(File file, String text) {
File temp = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
temp = File.createTempFile("temp", "temp");
pw = new PrintWriter(temp);
br = new BufferedReader(new FileReader(file));
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
if (line.equals(text)) {
continue;
}
pw.println(line);
}
pw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
safeClose(br);
safeClose(pw);
if (temp != null) {
file.delete();
temp.renameTo(file);
}
}
}
private static void safeClose(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
追问:着实看不懂,
public static void del() {// 删除内容
System.out.println("请输入文本文档地址:(盘符:\\文件名.txt)");
found = input.next();
System.out.println("请输入内容:");
String nei = input.next();
}
这是我的代码,能告我肿么写么
追答:public static void del() {// 删除内容
    System.out.println("请输入文本文档地址:(盘符:\文件名.txt)");
    found = input.next();
    System.out.println("请输入内容:");
    String nei = input.next();  
    delete(found, nei);
}
public static void delete(String file, String text) {
        delete(new File(file), text);
}
//这里把上面的三个方法复制下来,如果这都不会,那么你需要的是学习基础知识。
追问:这个……是两个方法吧……,下面那个方法里写上delete以后还提示让创建方法
追答:能看懂就好
  • 3楼网友:舍身薄凉客
  • 2021-01-11 08:02

你可以先定义一个InputStreamReader读取文本文件内容,然后再用一个LineNumberReader获取刚才InputStreamReader的对象,LineNumberReader里有个方法readLine()是用来一行一行的顺序读取字符,然后用一个判断语句来判断你想修改的行,最后删除或修改就可以了 。
.txt"),"GBK"));String c;while ((c=input.readLine())!=null) {ll.add(c);System.out.println(c);}input.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息