JavaIO之字节流操作

1.OutputStream写入文件内容

import java.io.*;
public class OutPutStreamDemo01 {
	public static void main(String[] args) throws Exception {
		//第1步:使用File类找到一个文件
		File f = new File(File.separator + "Users/QiuFeihu/Work/test/hello.txt");
		f.createNewFile();
		//第2步:通过子类实例化父类对象
		OutputStream out = null;            //准备好一个输出的对象
		out = new FileOutputStream(f);      //通过对象多态性,进行实例化
		//第3步:进行写操作
		String str = "Hello World!!!";      //准备一个字符串
		byte b[] = str.getBytes();          //只能输出byte数组,所以将字符串变为byte数组
        out.write(b);
        //第4步:关闭输出流
        out.close();
	}
}

2.InputStream读取文件内容

import java.io.*;
public class InputStreamDemo01 {
	public static void main(String[] args) throws Exception {
		//第1步:使用File类找到一个文件
		File f = new File(File.separator+"Users/QiuFeihu/Work/test/hello.txt");
		//第2步:通过子类实例化父类对象
		InputStream input = null;
		input = new FileInputStream(f);
		//第3步:进行读操作
		byte b[] = new byte[1024];
		input.read(b);
		//第4步:关闭输入流
		input.close();
		System.out.println("内容为:" + new String(b));
	}
}

    运行结果:

    内容为:Hello World!!!

    3.OutputStream追加文件内容:

import java.io.*;
public class OutputStreamDemo03 {
	public static void main(String[] args) throws Exception {
		//第1步:使用File类找到一个文件
		File f = new File(File.separator+"Users/QiuFeihu/Work/test/hello.txt");
		//第2步:通过子类实例化父类对象
		OutputStream out = null;
		out = new FileOutputStream(f,true);
		//第3步:进行写操作
		String str = "\r\n世界你好!";
		byte b[] = str.getBytes();
		for(int i = 0; i < b.length; i++){
			out.write(b[i]);
		}
		//第4步:关闭输出流
		out.close();

	}
}

   4.InputStream循环读取文件内容:

import java.io.*;
public class InputStreamDemo05 {
	public static void main(String[] args) throws Exception {
		//第1步:使用File类找到一个文件
		File f = new File(File.separator+"Users/QiuFeihu/Work/test/hello.txt");
		//第2步:通过子类实例化父类对象
		InputStream input = null;
		input = new FileInputStream(f);
		//第3步:进行读操作
		int len = 0;
		byte b[] = new  byte[1024];
		int temp = 0;
		while((temp = input.read()) != -1) {
			//将每次的读取内容给temp变量,如果temp的值不是-1,则表示文件没有读完
			b[len] = (byte)temp;
			len++;
		}
		//第4步:关闭输入流
		input.close();
		System.out.println("内容为:" + new String(b,0,len));
	}
}

    运行结果:

    内容为:Hello World!!!

    世界你好!

   

猜你喜欢

转载自tigerblog.iteye.com/blog/2213169