Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何编辑文件_Java_File - Fatal编程技术网

Java:如何编辑文件

Java:如何编辑文件,java,file,Java,File,我有以下代码可以用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

我有以下代码可以用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中编辑文件?

下面是如何使用新的java 7文件API来实现这一点(好吧,新的……java 8现在已经推出,所以这并不是新的):

//读取源文件中的所有行
最终路径源=Path.get(“/Path/to/source.txt”);
最终列表行=Files.readAllLines(源,StandardCharsets.UTF_8);
//询问必要的信息
//更新相关行
布尔发现;
国际电话号码;
弦线;
扫描仪;
对于(int index=0;index
不要“就地”编辑文件。将内容写入临时文件,然后重命名为原始文件。谢谢您的回答,先生!如果我直接在主文本文件中编辑文件,会有什么问题?首先,偏移量不会自动为您更新;假设您有“hello world”,然后写“再见”开始时,文件将包含“goodbyeorld”-->损坏。第二,即使尝试在同一文件中重写整个内容,如果由于某种原因写入失败,也会丢失所有内容:原始内容和要进行的修改。这就是为什么必须始终写入临时文件,然后才重命名为原始文件的原因。
// 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);