Ernest 是对的,因为从对象流中删除特定对象稍微复杂一些。他也是对的,当你想清空一个文件时,你可以简单地打开它进行写入并关闭它。但是,如果您想从文件系统中删除它,可以使用File
对象来完成(不要忘记处理异常并正确返回值)。以下示例可能并不完美,但它应该为您提供有关如何使用纯 Java 实现目标的提示。希望这可以帮助...
package test;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
String filename = "object.serialized";
{
List objects = new ArrayList();
objects.add("String1");
objects.add("String2");
objects.add("String3");
writeObjectsToFile(filename, objects);
}
{
List objects = readObjectsFromFile(filename);
objects.remove(1);
writeObjectsToFile(filename, objects);
}
{
List objects = readObjectsFromFile(filename);
for (Object object : objects) {
System.out.println(object);
}
}
emptyFile(filename);
deleteFile(filename);
}
private static void emptyFile(String filename) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(filename);
} finally {
if (os != null) {
os.close();
}
}
}
private static void deleteFile(String filename) {
File f = new File(filename);
if (f.delete()) {
System.out.println(filename + " deleted sucessfully...");
} else {
System.out.println(filename + " deletion failed!");
}
}
private static void writeObjectsToFile(String filename, List objects) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(os);
for (Object object : objects) {
oos.writeObject(object);
}
oos.flush();
} finally {
if (os != null) {
os.close();
}
}
}
private static List readObjectsFromFile(String filename) throws IOException, ClassNotFoundException {
List objects = new ArrayList();
InputStream is = null;
try {
is = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(is);
while (true) {
try {
Object object = ois.readObject();
objects.add(object);
} catch (EOFException ex) {
break;
}
}
} finally {
if (is != null) {
is.close();
}
}
return objects;
}
}
输出:
String1
String3
object.serialized deleted sucessfully...