我刚刚开始学习java,我找到了一个关于如何更新文本文件的示例,但我需要一些关于如何操作它以使用分隔符更新文本文件中的元素的指导。例如,如果我想用新地址编辑我的地址2
login,name,address,contact
login1,name1,address1,contact1
login2,name2,address2,contact2
File f=new File("appendOldFile.txt");
FileInputStream fs = null;
InputStreamReader in = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
String textinLine;
try {
fs = new FileInputStream(f);
in = new InputStreamReader(fs);
br = new BufferedReader(in);
while(true)
{
textinLine=br.readLine();
if(textinLine==null)
break;
sb.append(textinLine);
}
String textToEdit1 = "abc";
int cnt1 = sb.indexOf(textToEdit1);
sb.replace(cnt1,cnt1+textToEdit1.length(),"New Append text");
String textToEdit2 = "xyz";
int cnt2 = sb.indexOf(textToEdit2);
sb.replace(cnt2,cnt2+textToEdit2.length(),"Second new edit text");
fs.close();
in.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
首先,您必须使用并找到所需的登录名作为更改相应地址的 key 来迭代您的文件,为此我只是提示您使用谷歌或自己进一步搜索以获得顶部最好的结果。 如需进一步帮助回复...
File f=new File("C:/Users/Junaid Hassan/Contacts",FINAL1);
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String key;
while((key=br.readLine())!=null) //then you have to split the strings
String SPLIT[]=NAME.split(",");
String Login=SPLIT[0];
String Name=SPLIT[1];
String Address=SPLIT[2];
String Contact=SPLIT[3];
//then put a check that if your login will match a key
if(Login.equals(key)){
//here do what you want change the address
}
}
关于java - 更新文本文件定界符java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16260313/