java按行读取xml文件_按行读入xml文件,删除不需要的行 -Java

该Java程序演示了如何按行读取XML文件,将包含特定字符串(如'zhaoyueplc')的行写入单独的删除文件,而其他行则保存到新的XML文件中。它使用BufferedReader和BufferedWriter进行文件操作。
摘要由CSDN通过智能技术生成

删除挺麻烦的,这里其实只是把需要的行存到arraylist中再存到另一个文件中

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.ArrayList;

public class domainRealse {

public static void main(String[] args) throws IOException {

readFileByLines("E:\\wewew.xml");

}

private static void readFileByLines(String fileName) {

File file = new File(fileName);

BufferedReader reader = null;

ArrayList arrStr = new ArrayList();

ArrayList errStr = new ArrayList();

try {

System.out.println("以行读文件内容,一次读一整行:");

reader = new BufferedReader(new FileReader(file));

String tempString = null;// 每次读入都存在一个temp中

int line = 1;

while ((tempString = reader.readLine()) != null) {

if (-1 != tempString.indexOf("zhaoyueplc")) {

//如果此行有“zhaoyueplc”的字样,将其存入errStr

System.err.println("line " + line + ": " + tempString);

errStr.add(tempString);

} else {

//没有的话,存到arrStr

arrStr.add(tempString);

}

line++;

}

reader.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

BufferedWriter output = null;

try {

// arrStr写到result.xml

output = new BufferedWriter(new FileWriter("E:\\result.xml"));

for (String str : arrStr) {

output.write(str + "\t");

}

output.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (output != null) {

try {

output.close();

} catch (IOException e1) {

}

}

}

BufferedWriter output1 = null;

try {

//errStr写到”deletedItem中“

output1 = new BufferedWriter(new FileWriter("E:\\deletedItem.txt"));

for (String str : errStr) {

output1.write(str + "\n\t");

}

output1.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (output1 != null) {

try {

output1.close();

} catch (IOException e1) {

}

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值