Java 将字符串从数组替换为文件中的行
我的文件有:Java 将字符串从数组替换为文件中的行,java,arrays,string,file,Java,Arrays,String,File,我的文件有: public class MyC{ public void MyMethod() { System.out.println("My method has been accessed"); System.out.println("hi"); } } 下面的代码执行以下操作。 1.如果行计数等于num[index],它将检查该行是否包含 值1[索引]。如果为true,则替换VALUES[index]中第一个索引中的字符串,并写
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
下面的代码执行以下操作。
1.如果行计数等于num[index]
,它将检查该行是否包含
值1[索引]
。如果为true,则替换VALUES[index]
中第一个索引中的字符串,并写入新文件
2.如果num index不等于num[index]
,它只需按原样将行写入新文件
我遇到的问题是,在写入新文件后,原始的第1行和第2行仍然出现在新文件中。如何删除该选项。
这是我的密码:
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {1,2,4}; //Line Numbers
String[] VALUES = new String[] {"AB","BC","CD"}; //Correct Solutions
String[] VALUES1 = new String[] {"class","void","System"}; //To Replace
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
您应该添加一个指示器,以显示是否替换了此行 while(行!=null){
boolean exists=false;
对于(int index=0;index在代码中注释此行
writer1.write(line+System.getProperty("line.separator"));
然后试试看这已经不是你在具体项目中提出错误的第一个问题。如果你全面回顾你为实现你的想法而选择的方法,可能会更好吗?我正在零碎地实施项目。我面临的问题和找不到解决方案,我指的是网站。谢谢。谢谢,只有一行需要替换上面Kai的回答非常有效。
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
exists = true;
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));
writer1.write(line+System.getProperty("line.separator"));