我的程序有以下代码,
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);
方法获取数据但是如何为该特定用户进行更改?我真的很困惑。
答案 0 :(得分:1)
您必须制作每个记录的可序列化对象,然后访问它并按如下所示进行更新,
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; }
}
这样做。让我知道是否有任何问题。
答案 1 :(得分:1)
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);
2)对于一个大文件
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);