IO基本操作

package test;

import java.io.*;

public class IOTest2 {

	static String path1 = "src/test/a.txt";
	static String path2 = "src/test/b.txt";

	public static void main(String[] args) {
		//字节流	
		readFile1();
		//字符流
		readFile2();
		//字节流缓存流
		readFile3();
		//字符缓存流
		readFile4();
	
		//字节流
		writeFile1();              
		//字符流
		writeFile2();
		//字节缓存流
		writeFile3();
		//字符缓存流
		writeFile4();
	}
	private static void writeFile4() {
		File file = new File(path2);
		Writer writer = null;
		BufferedWriter bw = null;
		try {
			writer = new FileWriter(file);
			bw = new BufferedWriter(writer);
			String str = "骄傲后来开始放假啊包括了是吧";
			bw.write(str);
			
		}//抛异常+关闭
		
	}
	private static void readFile4() {
		File file = new File(path1);
		Reader reader = null;
		BufferedReader br = null;
		try {
			reader = new FileReader(file);
			br = new BufferedReader(reader);
			String str = null;
			while((str = br.readLine()) != null) {
				System.out.println(str);
			}
			
		} //抛异常+关闭
	}
	private static void readFile1() {

		File file = new File(path1);
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			byte [] bytes = new byte [1000];
	   		is.read(bytes);
			String str = new String (bytes);
			System.out.println(str);
		}//抛异常+关闭
	}	
			
	private static void writeFile3() {
		File file = new File(path2);
		OutputStream os = null;
		BufferedOutputStream bos= null;
		try {
			os = new FileOutputStream(file);
			bos = new BufferedOutputStream(os);
			String str = "sadfalhnsdf;klasdhnf";
			bos.write(str.getBytes());
		} //抛异常+关闭
	}

	private static void readFile3() {
		
		File file = new File(path1);
		InputStream is = null;
		BufferedInputStream bis= null;
		try {
			is = new FileInputStream(file);
			bis = new BufferedInputStream(is);
			byte [] bytes = new byte [1000];
			bis.read(bytes);
			String str = new String (bytes);
			System.out.println(str);
		}//抛异常+关闭
	}

	private static void writeFile2() {
		File file = new File(path2);
		Writer writer = null;
		try {
			writer = new FileWriter(file);
			writer.write("aoifjaopfhaowuihaiwpfhaoi");
		} //抛异常+关闭
	}

	private static void writeFile1() {
		File file = new File(path2);
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			String str = "sadfalhnsdf;klasdhnf";
			os.write(str.getBytes());
		}//抛异常+关闭
	}

	private static void readFile2() {
		File file = new File(path1);
		Reader reader = null;
		try {
			reader = new FileReader(file);
			int i = -1;
			while( (i = reader.read())!= -1) {
				System.out.print((char)i);
			}
			
		} //抛异常+关闭
}
}

byte->String :  String str = new String (bytes)
String->byte:   str.getBytes();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值