javafile替换_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"};java replace方法
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = place(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();
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("");
BufferedReader br = new BufferedReader(new InputStreamReader(fs)); FileWriter writer1 = new FileWriter("");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = (count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.Property("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
标签:java
来源: /bug/20191013/1908106.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。