字节流读出文件内容并打印:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ReadByteStream { public static void main(String[] args) { try { FileInputStream fis=new FileInputStream("test.txt"); byte input[]=new byte[10]; fis.read(input); String inputString=new String(input,"UTF-8"); System.out.println(inputString); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
输出10个字节的内容。
字节流把数据写入文件:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class WriteByteStream { public static void main(String[] args) { try { FileOutputStream fos=new FileOutputStream("testw.txt"); String outString ="write 123456写出数据"; byte output[]=outString.getBytes("UTF-8"); fos.write(output); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
程序会把"write 123456写出数据"写入文件testw.txt中。
利用字节流读写拷贝数据:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class CopybyByteStream { public static void main(String[] args) { try { FileInputStream fis=new FileInputStream("ani.gif"); FileOutputStream fos=new FileOutputStream("ani_new.gif"); byte input[]=new byte[50]; while(fis.read(input)!=-1) { fos.write(input); } fis.close(); fos.close(); System.out.println("完成拷贝"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
程序会把"ani.gif"拷贝到"ani_new.gif"中。