Java二进制以及TXT文件操作
TXT文件操作
创建txt文件,并将内容写入txt文件
public static void SaveText() throws IOException{
String name="zzz";
String Myclass="软件工程";
String ID="2017211";
File file=new File(".\\name.txt");
FileWriter fw=new FileWriter(file);
if(!file.exists()){
file.createNewFile();
}
if(file.exists()){
fw.write(name);
fw.write(Myclass);
fw.write(ID);
fw.close();
}
}
二进制文件操作
将数据存入二进制文件
public static void writeFSList(int[] a) throws IOException{
File file=new File(".\\test.dat");
if(!file.exists()){
DataOutputStream os = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(file)));
for(int i=0;i<a.length;i++){
os.writeInt(a[i]);
}
os.flush();
os.close();
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
ObjectOutputStream oos=new ObjectOutputStream(fos);
for(int i=0;i<a.length;i++){
oos.write(a[i]);
}
System.out.println("文件已存入");
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将数据从二进制文件中读出
public ArrayList<q2> outQ2Object() throws IOException{
BufferedInputStream bufferInput = null;
DataInputStream dataInput = null;
ArrayList<q2> studentouts = new ArrayList<q2>();
try {
bufferInput = new BufferedInputStream(
new FileInputStream(".\\q2.dat"));
dataInput = new DataInputStream(bufferInput);
int size = dataInput.readInt();
for (int i = 0; i < size; i++) {
q2 student = new q2();
student.ID=dataInput.readInt();
student.AverageGrade=dataInput.readDouble();
student.PerforScore=dataInput.readDouble();
student.overallScore=dataInput.readDouble();
studentouts.add(student);
}
printQ2(studentouts);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
dataInput.close();
}
return studentouts;
}