java file替换_java-用另一个字符串替换File中的行

我有一个包含以下内容的文本文件:

public class MyC{

public void MyMethod()

{

System.out.println("My method has been accessed");

System.out.println("hi");

}

}

我有一个数组num [] = {2,3,4};包含要用此数组中的字符串完全替换的行号

String [] VALUES = new String [] {“ AB”,“ BC”,“ CD”};

也就是说,第2行将被AB替换,第3行将被BD替换,ine 4被替换为CD.

不在num [] array中的行必须与所做的更改一起写入新文件.

到目前为止,我已经尝试过几种循环,但仍然无法正常工作.

public class ReadFileandReplace {

/**

* @param args

*/

public static void main(String[] args) {

try {

int num[] = {3,4,5};

String[] VALUES = new String[] {"AB","BC","CD"};

int l = num.length;

FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(fs));

LineNumberReader reader = new LineNumberReader(br);

FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");

String line;

int count =0;

line = br.readLine();

count++;

while(line!=null){

System.out.println(count+": "+line);

line = br.readLine();

count++;

int i=0;

if(count==num[i]){

int j=0;;

System.out.println(count);

String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();

j++;

writer1.write(newtext);

}

i++;

writer1.append(line);

}

writer1.close();

}

catch (IOException e) {

e.printStackTrace();

} finally {

}

}

}

预期的输出应如下所示:

public class MyC{

AB

BC

CD

Sys.out.println("hi");

}

}

当我运行代码时,所有行都显示在同一行上.

解决方法:

您差不多完成了,我已经用地图更新了您的代码.检查一下

int num[] = {3, 4, 5};

String[] values = new String[]{"AB", "BC", "CD"};

HashMap lineValueMap = new HashMap();

for(int i=0 ;i

lineValueMap.put(num[i],values[i]);

}

FileInputStream fs = new FileInputStream("test.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(fs));

FileWriter writer1 = new FileWriter("test1.txt");

int count = 1;

String line = br.readLine();

while (line != null) {

String replaceValue = lineValueMap.get(count);

if(replaceValue != null) {

writer1.write(replaceValue);

} else {

writer1.write(line);

}

writer1.write(System.getProperty("line.separator"));

line = br.readLine();

count++;

}

writer1.flush();

标签:java

来源: https://codeday.me/bug/20191013/1908106.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值