標籤:
package fileoutputstream;import java.io.FileInputStream;import java.io.FileOutputStream;public class CopyFileDemo {public static void main(String[] args) throws Exception {//封裝資料來源FileInputStream fis = new FileInputStream("fos.txt");//fos.txt檔案必須的存在FileOutputStream fos = new FileOutputStream("write.txt");//write.txt檔案可以先不存在//複製資料()byte[] bys = new byte[1024];int len=0;while((len=fis.read(bys))!=-1){fos.write(bys,0,len);//一次寫入一個位元組數組}//釋放資源fos.close();fis.close();}}
一次讀取一個位元組(字元),或者一次多去一個位元組數組(字元數組)
package filereader;import java.io.FileReader;public class FileReader11 {public static void main(String[] args) throws Exception {////方式一:一次讀取一個位元組//FileReader reader = new FileReader("fos.txt");////int by = 0;//while((by=reader.read())!=-1){////System.out.println(by);//System.out.print((char)by);//}//reader.close();//方式二:一次讀取一個位元組數組FileReader reader2 = new FileReader("fos.txt");char[] ch = new char[5];//byte[] bys = new byte[1024];int len=0;while((len=reader2.read(ch))!=-1){System.out.println(new String(ch,0,len));}reader2.close();}}
最終版把讀取的檔案顯示在控制台:
package fileoutputstream;import java.io.FileInputStream;public class FileOutputStream4 {public static void main(String[] args) throws Exception {FileInputStream fis = new FileInputStream("fos.txt");//最終版代碼//數組的長度一般是1024或者1024的整數倍byte[] bys = new byte[1024];int len=0;while((len=fis.read(bys))!=-1){System.out.println(new String(bys,0,len));//new String是把字節數組轉為字串}}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java檔案流之copy檔案(用一次讀取一個位元組數組方式)