我有以下代码用Java编辑我的.txt文件:
public static void editInfo() throws IOException
{
Scanner inFile2 = new Scanner( new FileReader ("FileOut.txt"));
int id_number = Integer.parseInt(JOptionPane.showInputDialog(
"Enter Id number to be searched: "));
String copy = "";
while (inFile2.hasNext())
{
int idnumber = inFile2.nextInt();
String firstname = inFile2.next();
String lastname = inFile2.next();
if (id_number == idnumber)
{
firstname = JOptionPane.showInputDialog("Enter First Name : ");
lastname = JOptionPane.showInputDialog("Enter Last Name : ");
copy += idnumber + " " + firstname + " " + lastname + "\n";
}
else
{
copy += idnumber + " " + firstname + " " + lastname + "\n";
}
}
add(copy); //Method that writes a string into the
JOptionPane.showMessageDialog(null, "Information Successfully updated" , "edit information" , JOptionPane.INFORMATION_MESSAGE);
inFile2.close();
}
我的问题是,还有其他更简单的方法可以在java中编辑文件吗?
答案 0 :(得分:0)
以下是如何使用新的Java 7文件API(嗯,新... Java 8现在出来,所以这不是新的):
// Read all lines from source file
final Path source = Paths.get("/path/to/source.txt");
final List<String> lines = Files.readAllLines(source, StandardCharsets.UTF_8);
// Ask for necessary information
// Update relevant line
boolean found;
int idnumber;
String line;
Scanner scanner;
for (int index = 0; index < lines.size(); index++) {
line = lines.get(index);
scanner = new Scanner(line);
idnumber = scanner.nextInt();
if (idnumber != id_number) // not the good line
continue;
found = true;
firstname = JOptionPane.showInputDialog("Enter First Name : ");
lastname = JOptionPane.showInputDialog("Enter Last Name : ");
lines.set(index, String.format("%d %s %s", idnumber, firstname, lastname);
break; // no need to go further
}
if (!found) {
JOptionPane.showMessageDialog(null, "Index not found" , "oops" ,
JOptionPane.WARNING_MESSAGE);
return;
}
//Create a temporary file to write the modified contents
final Path tmpfile = Files.createTempFile("temp", ".txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(tmpfile,
StandardCharsets.UTF_8);
) {
for (final String line: lines) {
writer.write(line);
writer.newLine();
}
}
// Rename to original file
Files.move(tmpfile, source, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "Information Successfully updated" ,
"edit information" , JOptionPane.INFORMATION_MESSAGE);