存儲與讀入是程式中不可避免的兩項操作,畢竟在一般的情況下,我們的資料都是存儲在記憶體中的,一旦程式終止或者斷電,這些資料就全部消失了,要想儲存它們,就必須輸出檔案讀入檔案。
今天我們要談的,就是這個記憶體->外存,外存->記憶體的過程
1,C++的檔案讀入,輸出
通過ifstream類,ofstream類這兩個類實作。
在使用這兩個類進行資料讀入讀出的時候,首先,要建立他們的對象。然後,要給它們對應的路徑
ofstream outfile;
ifstream infile;
infile.open("C:\\Users\\32809\\Desktop\\program\\working\\tr4\\in.txt",ios::in);
outfile.open("C:\\Users\\32809\\Desktop\\program\\working\\tr4\\out.txt",ios::out);
之後,就完全可以按照cin,cout的輸出輸入流去存儲了
infile>>a>>b>>c>>ag>>sc>>ar>>it>>ra;
outfile<<setw(8)<<"學号"<<setw(8)<<"姓名"<<setw(8)<<"性别"<<setw(8)<<"年齡"
<<setw(12)<<"課程成績"<<setw(8)<<"專業"
<<setw(8)<<"總成績"<<endl;
值得注意的是,據筆者所知,C++并沒有直接存儲對象的庫,是以說,需要的時候,就隻能直接重載函數了。
這裡舉一個例子
ostream &operator<<(ofstream& output,stu &a)
{
output<<setw(8)<<a.num<<setw(8)<<a.name<<setw(8)<<a.sex<<setw(8)<<a.age<<setw(12)<<a.sco
<<setw(8)<<a.sub<<setw(8)<<a.scoa;
return output;
}
這樣就可以把對象直接輸出了
2,java檔案的輸入輸出
首先,我們先引入幾個包。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
然後容我在代碼中重點介紹其中的FileOutputStream,FileReader。
/*
輸入檔案部分
*/
ile file = new File("C:\\Users\\32809\\Desktop\\wen.txt");
//将資料寫到指定檔案
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if(!file.exists()){//這裡的問題是目标檔案是否存在,如果不存在,建立一個,如果存在,直接寫入
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String importNum="";
importNum=importNum+score+' '+time+' '+broad.x1+' '+broad.y1+' '+broad.vx+' '+broad.vy;
for(int i=0;i<ball.length;i++)
{
if(ball[i]!=null)
{
importNum=importNum+' '+ball[i].x1+' '+ball[i].y1+' '+ball[i].vx+' '+ball[i].vy+' '+ball[i].r;
}
}
byte[] buffer = importNum.getBytes();//把資料存入字元數組中
//将buffer中的資料寫到指定的檔案中了
try {
fos.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
輸出檔案部分
*/
File file = new File("C:\\Users\\32809\\Desktop\\wen.txt");//打開檔案夾
FileReader fr=null;
try {
fr = new FileReader(file);//建立讀入
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
char length;
//System.out.println("null3");
try {
while((length=fr.read())!=-1){//循環讀取指定檔案的内容
if(length==32) inputnum+=' ';
else inputnum+=length;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
相比之下,java的檔案存儲似乎比c++複雜了很多,但實際上上隻是多出來很多異常處理,這些編譯器都能夠自動添加,是以難度并沒有大多少,換而言之,功能上也并沒有豐富多少
但實際上,java的一個特點在于它能夠輸入輸出對象,這裡就需要java.io.ObjectInputStream
首先,第一點,也是其他文章經常放到最後一點說的問題,就是類的可序列化。
隻有對象支援java.io.Serializable或java.io.Externalizable接口的才能夠被從流中讀取。
符合上面條件的,我們隻要添加implements Serializable就可以了。
之後的操作筆者推薦一篇非常标準的文章給大家,https://blog.csdn.net/u010982856/article/details/52300298
這位的代碼寫的非常合适,我就是從他那裡學習的,想想寫個差不多一樣的代碼放上來也不大好意思,就放上師傅的代碼給大家參考吧。