2014-03-19 64 views
0

我有下面的代碼編輯我的.txt文件中的Java:的Java:如何編輯文件

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

做**不**編輯文件「到位」。將內容寫入臨時文件_then_重命名爲原始文件。 – fge

回答

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); 
+0

謝謝你的答案先生! 如果我直接編輯主文本文件中的文件,問題是什麼先生? – toxicrain

+1

首先,偏移量不會自動爲您更新;假設你有「hello world」,並且你在開頭寫了「goodbye」,那麼文件將包含「goodbyeorld」 - >腐敗。其次,即使您嘗試重寫同一文件中的全部內容,但如果由於某種原因而導致寫入失敗,則會失去一切:原始內容和您想要進行的修改。這就是爲什麼你必須總是寫入一個臨時文件,然後重命名爲原始文件。 – fge