FileOutputStream write()
package cn.itcast_01;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 字节输出流操作步骤:
* A:创建字节输出流对象
* B:调用write()方法
* C:释放资源
*
* public void write(int b):写一个字节
* public void write(byte[] b):写一个字节数组
* public void write(byte[] b,int off,int len):写一个字节数组的一部分
*/
public class FileOutputStreamDemo2 {
public static void main(String[] args) throws IOException {
// 创建字节输出流对象
// OutputStream os = new FileOutputStream("fos2.txt");// 多态
FileOutputStream fos = new FileOutputStream("fos2.txt");
//调用write()方法
// public void write(int b):写一个字节
// fos.write(97);
// public void write(byte[] b):写一个字节数组
byte[] bytes = { 97, 98, 99, 100, 101 };
fos.write(bytes);
// public void write(byte[] b,int off,int len):写一个字节数组的一部分
fos.write(bytes, 1, 3);// abcdebcd
fos.close();
}
}
FileInputStream read()
1.read
这个方法是对这个流一个一个字节的读,返回的int就是这个字节的int表示方式
以下是代码片段,经过测试当eclipse的编码为gbk时,转化出的字符串不需经过重新编码,如果eclipse的编码为utf-8时则由byte转成字符串需重新编成utf-8的InputStream in = Test.class.getResourceAsStream(“/tt.txt”);
byte[]tt=new byte[15];//测试用的事前知道有15个字节码 while(in.available()!=0){
for(int i=0;i<15;i++){
tt[i]=(byte)in.read(); } } String ttttt=new String(tt,”utf-8”); System.out.println(ttttt); in.close();2.read(byte[] b)
这个方法是先规定一个数组长度,将这个流中的字节缓冲到数组b中,返回的这个数组中的字节个数,这个缓冲区没有满的话,则返回真实的字节个数,到未尾时都返回-1in = Test.class.getResourceAsStream(“/tt.txt”); byte [] tt=new
byte[1024]; int b; while((b=in.read(tt))!=-1){
System.out.println(b); String tzt=new String(tt,”utf-8”);System.out.println(tzt);
3.read(byte[] b, int off, int len)
此方法其实就是多次调用了read()方法InputStream in = Test.class.getResourceAsStream(“/tt.txt”);
//System.out.println(in.available());//此方法是返回这个流中有多少个字节数,可以把数组长度定为这个
byte[]tt=new byte[in.available()]; int z; while((z=in.read(tt, 0, tt.length))!=-1){ System.out.println(new
String(tt,”utf-8”)); }
收集总结于:http://blog.csdn.net/l1585931143/article/details/54917470
http://blog.csdn.net/amo_te_ama_me/article/details/40587997