Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.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_Fileupdate - Fatal编程技术网

如何用Java更新文件,应该使用哪个类?

如何用Java更新文件,应该使用哪个类?,java,file,fileupdate,Java,File,Fileupdate,我的程序有以下代码 BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File("xyz.dat"),true)); bufWriter.write(nameField+"/"+ageField+"/"+genderField+"\n"); bufWriter.flush(); 这将创建一个文件。。 文件中存储的数据的样

我的程序有以下代码

BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File("xyz.dat"),true));
                        bufWriter.write(nameField+"/"+ageField+"/"+genderField+"\n");
                        bufWriter.flush();
这将创建一个文件。。 文件中存储的数据的样本格式

Name1/Age1/Gender1                            // for user1
Name2/Age2/Gender2                            // for user2
.
.
.
NameN/AgeN/GenderN                            //for userN

假设我需要更改用户的年龄5,那么我该怎么做呢?我可以导航到第5个用户,我可以通过
split(“/”,3)获取数据方法,但如何为特定用户进行更改?我在这里真的很困惑。

您必须创建每条记录的可序列化对象,然后访问它并按如下所示进行更新

import java.io.*;

public class phoneBook {
private ObjectOutputStream output;
private ObjectInputStream input;
File fileName = new File("d:\\java\\data\\phone.dat");

public static void main(String[] args) {
   phoneBook pb = new phoneBook();
   pb.writeFile(); // open, write and close the file
   pb.readFile(); // open, read and close the file
}

public void writeFile() {

   // I could have put this into an array which would have told me how many
   // records i have, it could then have be used in the readFile method below
   // but lets keep things very simple
   Record r1 = new Record("Paul Valle", "0207-568-789");
   Record r2 = new Record("Lorraine Valle", "0207-345-356");
   Record r3 = new Record("Dominic Valle", "0207-765-693");
   Record r4 = new Record("Jessica Valle", "0207-789-876");

   try {
      // Open a file handle for writing
      output = new ObjectOutputStream( new FileOutputStream( fileName));

      // Write some data to the file it could throw
      // InvalidClassException or NotSerializableException exceptions
      output.writeObject( r1 );
      output.writeObject( r2 );
      output.writeObject( r3 );
      output.writeObject( r4 );

      // Flush the ObjectOutputStream. This will write any buffered
      // output bytes and flush through to the FileOutputStream
      output.flush();

      // Close the file
      output.close();
   } catch (InvalidClassException icex) {
      System.out.println("Invalid Class");
   } catch (NotSerializableException nsex) {
      System.out.println("Object is not serializable");
   } catch (IOException e) {
      System.out.println("Problems either flushing or closing file");
   }
}

public void readFile() {
   Record r; // this object will hold the records when retrieved from the file

   try {
      // Open the file handle for reading
      input = new ObjectInputStream( new FileInputStream(fileName));

      // I know i have 4 records so lets read them, this is where i could have used the array
      // by using the length of the array i would have know how many records i have.
      for (int i = 0; i < 4; i++ ) {
         // Here we implicity cast the retrieved Object
         r = ( Record ) input.readObject();
         if (r.getName() == 'YOURMATCHINGNAME')
          {
               r.setName("NEWNAME");
               r.setPhone("NEWPHONENUMBER");  
               try {
                      // Open a file handle for writing
                      output = new ObjectOutputStream( new FileOutputStream( fileName));

                     // Write same data to the file it could throw
                     // InvalidClassException or NotSerializableException exceptions
                     output.writeObject( r );

                     // Flush the ObjectOutputStream. This will write any buffered
                    // output bytes and flush through to the FileOutputStream
                    output.flush();

                    // Close the file
                   output.close();
                   } catch (InvalidClassException icex) {
                       System.out.println("Invalid Class");
                   } catch (NotSerializableException nsex) {
                      System.out.println("Object is not serializable");
                   } catch (IOException e) {
                      System.out.println("Problems either flushing or closing file");
                  }  
                 finally{
                    break;
                  }  
          }  

      }

      // Close the file
      input.close();

   } catch (EOFException eofex) {
      System.out.println("No more records to read");
   } catch (ClassNotFoundException cnfex) {
      System.out.println("Unable to create object - class not found");
   } catch (IOException e ) {
      System.out.println("Unable to close file");
   }
 }
}

 // Serialization involves saving the current state of an object to a stream,
 // and restoring an equivalent object from that stream.
class Record implements Serializable {

private String name;
private String phone;

// Constructor
public Record() { this ("", ""); }

// Overloaded Constructor
public Record(String n, String p) {
   name = n;
   phone = p;
}

// The get and set methods
 public void setName(String n) { name = n; }

 public void setPhone(String p) { phone = p; }

 public String getName() { return name; }

 public String getPhone() { return phone; }
}
import java.io.*;
公共类电话簿{
私有对象输出流输出;
私有对象输入流输入;
文件名=新文件(“d:\\java\\data\\phone.dat”);
公共静态void main(字符串[]args){
电话簿pb=新电话簿();
pb.writeFile();//打开、写入和关闭文件
pb.readFile();//打开、读取和关闭文件
}
公共无效写入文件(){
//我可以把这个放进一个数组,它会告诉我有多少个
//如果我有记录,那么它就可以用在下面的readFile方法中
//但是让我们保持简单
记录r1=新记录(“Paul Valle”,“0207-568-789”);
记录r2=新记录(“Lorraine Valle”,“0207-345-356”);
记录r3=新记录(“多米尼克·瓦勒”,“0207-765-693”);
记录r4=新记录(“Jessica Valle”,“0207-789-876”);
试一试{
//打开文件句柄进行写入
output=newobjectoutputstream(newfileoutputstream(fileName));
//向它可能抛出的文件写入一些数据
//InvalidClassException或NotSerializableException异常
output.writeObject(r1);
output.writeObject(r2);
output.writeObject(r3);
output.writeObject(r4);
//刷新ObjectOutputStream。这将写入任何缓冲
//输出字节并刷新到FileOutputStream
output.flush();
//关闭文件
output.close();
}捕获(InvalidClassException icex){
System.out.println(“无效类”);
}捕获(NotSerializableException nsex){
System.out.println(“对象不可序列化”);
}捕获(IOE异常){
System.out.println(“刷新或关闭文件的问题”);
}
}
公共void readFile(){
记录r;//从文件检索时,此对象将保存记录
试一试{
//打开文件句柄进行读取
输入=新对象输入流(新文件输入流(文件名));
//我知道我有4条记录,所以让我们读取它们,这是我可以使用数组的地方
//通过使用数组的长度,我可以知道我有多少条记录。
对于(int i=0;i<4;i++){
//这里我们隐式转换检索到的对象
r=(记录)input.readObject();
如果(r.getName()=='YOURMATCHINGNAME')
{
r、 设置名称(“新名称”);
r、 设置电话(“新电话号码”);
试一试{
//打开文件句柄进行写入
output=newobjectoutputstream(newfileoutputstream(fileName));
//向可能抛出的文件写入相同的数据
//InvalidClassException或NotSerializableException异常
output.writeObject(r);
//刷新ObjectOutputStream。这将写入任何缓冲
//输出字节并刷新到FileOutputStream
output.flush();
//关闭文件
output.close();
}捕获(InvalidClassException icex){
System.out.println(“无效类”);
}捕获(NotSerializableException nsex){
System.out.println(“对象不可序列化”);
}捕获(IOE异常){
System.out.println(“刷新或关闭文件的问题”);
}  
最后{
打破
}  
}  
}
//关闭文件
input.close();
}捕获(EOFEException eofex){
System.out.println(“不再读取记录”);
}捕获(ClassNotFoundException cnfex){
System.out.println(“无法创建对象-找不到类”);
}捕获(IOE异常){
System.out.println(“无法关闭文件”);
}
}
}
//序列化涉及将对象的当前状态保存到流,
//以及从该流中恢复等效对象。
类记录实现可序列化{
私有字符串名称;
私人电话;
//建造师
公共记录(){this(“,”);}
//重载构造函数
公共记录(字符串n,字符串p){
name=n;
电话=p;
}
//get和set方法
public void setName(字符串n){name=n;}
公共void setPhone(字符串p){phone=p;}
公共字符串getName(){return name;}
公共字符串getPhone(){return phone;}
}
这样就可以了。如果有问题,请告诉我。

1)使用Java 7的短文件(适合内存)解决方案

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
String line5 = replaceAge(lines.get(4), newAge);
lines.set(4, line5);
Path tmp = Files.createTempFile(prefix, suffix, attrs);
Files.write(path, lines)
Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);

使用BufferedWriter方法,您必须读取整个文件,更改记录并将其保存回磁盘。您可以使用RandomAccessFile查找特定记录(行),读取并更新它并保存文件-但是,实现这一点并不简单,您必须管理记录边界等。其他选项是为每个用户保留1个文件数据,并使用用户名索引(例如user5.data)保存它。然后您可以读取user5.data并更新它。
    Path tmp = Files.createTempFile(prefix, suffix, attrs);
    try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
            BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
        String line;
        for (int i = 1; (line = br.readLine()) != null; i++) {
            if (i == 5) {
                line = replaceAge(line, newAge);
            }
            bw.write(line);
            bw.newLine();
        }
    }
    Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);