Java——IO流(字符输入输出流)_3

1、字符输入流

package IOTest_3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class TestReader_1 {
	public static void main(String[] args) {
		File src = new File("abc.txt");
		Reader re = null;
		try {
			re = new FileReader(src);
			int temp;
			while((temp=re.read())!=-1) {
				System.out.print((char)temp);
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}try {
			re.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

2、分段字符输入流

package IOTest_3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class TestReader_2 {
	public static void main(String[] args) {
		File src = new File("abc.txt");
		Reader re = null;
		try {
			re = new FileReader(src);
			char[] c = new char[10];
			int len;
			while((len = re.read(c))!=-1) {
				System.out.println(new String(c,0,len));
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				re.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

3、字符输出流

package IOTest_3;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class TestWriter_3 {
	public static void main(String[] args) {
		File src = new File("test.txt");
		FileWriter write = null;
		try {
			write = new FileWriter(src,true);
			//第一种方法
			write.write("write测试1\r\n");
			write.write("write测试2\r\n");
			//第二种
			String msg = "你好,IO流\r\n";
			char[] c = msg.toCharArray();
			write.write(c, 0, c.length);
			//第三种
			write.append("你好,");
			write.append("Java");			
			write.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(write!=null) {
					write.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/Asdzxc968/article/details/88368525
今日推荐