java檔案流之copy檔案(用一次讀取一個位元組數組方式)

來源:互聯網
上載者:User

標籤:

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檔案(用一次讀取一個位元組數組方式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.