这是一个程序,它允许用户搜索一个项目,然后程序将项目拆分并将它们存储在 4 个不同的textfields
. 但是,以下是将检索到的项目更新回文件的方法。问题是每当用户单击更新按钮时,该行确实更新成功,但文件中的其他行被删除!
我正在使用一个arraylist
来存储搜索到的项目以及临时文件来写入项目然后重命名它。
file.txt
ramal hotel1 10 uk
bren hotel2 20 france
gil hotel3 30 china
//Update to file
button9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try {
String stringSearch = textfield1.getText();
File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
File file = new File("file.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while (( line = bf.readLine()) != null){
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String a = textfield1.getText();
String b = textfield2.getText();
String c = textfield3.getText();
String d = textfield4.getText();
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
String thirdword = word[2];
String fourthword = word[3];
writer.write(line.replace("\t", "\t").replace(firstword, b).replace(secondword, c).replace(thirdword, d));
writer.flush();
}
writer.newLine();
}
writer.close();
bf.close();
filetemp.renameTo(file);
filetemp.deleteOnExit();
FileChannel src = new FileInputStream(filetemp).getChannel();
FileChannel dest = new FileOutputStream(file).getChannel();
dest.transferFrom(src, 0, src.size());
}catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
});