InputStream OutputStream
利用InputStream 和 OutputStream實作copy file 和 move file。
InputStream 跟 OutputStream是兩根管子,所有讀進來的東西,都先灌進inputStream裡,所有要寫入的都放進OutputStream裡。接下來的操作就只要從InputStream 和 OutputStream下手即可。如此一來,對於不同的資料來源就變的方便處理,
如網路連線的資料
URL url=new URL(arg[0]);
URLConnection urlc=url.openConnection();
InputStream ins=urlc.getInputStream();
如對socket的讀取
Socket s = new Socket("www.idon'tknow.com", 1111);
InputStream ins = s.getInputStream();
如處理檔案
InputStream inStream = new FileInputStream(afile);
接下來我們看看move file 跟 copy file的實作。
move file的實作
public static void move(String inputfile, String outputfile) //inputfile 和 outputfile 要絕對路徑
{
try{
File afile =new File(inputfile);
File bfile =new File(outputfile);
InputStream inStream = new FileInputStream(afile);
OutputStream outStream = new FileOutputStream(bfile);
//InputStream跟OutputStream都是以byte為單位在處理資料
byte[] buffer = new byte[(int) afile.length()];
int length=inStream.read(buffer);
outStream.write(buffer, 0, length);
inStream.close();
outStream.close();
//delete the original file
afile.delete();
}catch(IOException e){
e.printStackTrace();
}
}
copy file 的實作
public static void copy(String inputfile, String outputfile) // inputfile 和 outputfile 要絕對路徑
{
try{
File afile =new File(inputfile);
File bfile =new File(outputfile);
InputStream inStream = new FileInputStream(afile);
OutputStream outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[(int) afile.length()];
int length=inStream.read(buffer);
outStream.write(buffer, 0, length);
inStream.close();
outStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
留言
張貼留言