java---输入输出流(三)

转换流

OutputStreamWriter

转换流 :
java.io.OutputStreamWriter 继承Writer类,就是一个字符输出流,写文本文件
write( )字符,字符数组,字符串

字符通向字节的桥梁,将字符流转字节流

public static void writeCN() throws Exception {
		//创建与文件关联的字节输出流对象
		FileOutputStream fos = new FileOutputStream("c:\\cn8.txt");
		//创建可以把字符转成字节的转换流对象,并指定编码
		OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
		//调用转换流,把文字写出去,其实是写到转换流的缓冲区中
		osw.write("你好");//写入缓冲区。
		osw.close();
	}

InputStreamReader
字节通向字符的桥梁,将字符流转字节流

缓冲流

字节缓冲输出BufferedOutputStream

构造方法
public BufferedOutputStream(OutputStream out)创建一个新的缓冲输出流,以将数据写入指定的底层输出流。

public class BufferedOutputStreamDemo01 {
	public static void main(String[] args) throws IOException {
		
		//写数据到文件的方法
		write();
	}

	/*
	 * 写数据到文件的方法
	 * 1,创建流
	 * 2,写数据
	 * 3,关闭流
	 */
	private static void write() throws IOException {
		//创建基本的字节输出流
		FileOutputStream fileOut = new FileOutputStream("abc.txt");
		//使用高效的流,把基本的流进行封装,实现速度的提升
		BufferedOutputStream out = new BufferedOutputStream(fileOut);
		//2,写数据
		out.write("hello".getBytes());
		//3,关闭流
		out.close();
	}
}

字节缓冲输入流 BufferedInputStream

构造方法
public BufferedInputStream(InputStream in)

字符缓冲流

  • 字符缓冲输入流 BufferedReader

方法
public String readLine() 读取一个文本行,包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null

  • 字符缓冲输出流 BufferedWriter

方法:
void newLine() 根据当前的系统,写入一个换行符

/*
 * BufferedReader 字符缓冲输入流
 * 
 * 方法:
 * 	String readLine() 
 * 需求:从文件中读取数据,并显示数据
 */
public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		//1,创建流
		BufferedReader in = new BufferedReader(new FileReader("file.txt"));
		//2,读数据
		//一次一个字符
		//一次一个字符数组
		//一次读取文本中一行的字符串内容
		String line = null;
		while( (line = in.readLine()) != null ){
			System.out.println(line);
		}
		
		//3,关闭流
		in.close();
	}
	}

Properties集合

  • properties集合,他是唯一一个能与IO流交互的集合
public classPropertiesDemo1{
public static void main(String[  ] args){
//创建集合对象
Properties prop = new Properties(  );
//添加元素到集合
//prop.put(可以,value);
prop.setProperty(“周迅”,“张学友”);
prop.setProperty("李小璐“,”贾乃亮“);
prop.setProperty(”杨幂“,”刘恺威“);

//System.out.println(prop);//测试的使用
、、不按理集合
Set<String> keys = prop.stringPropertyNames( );
for  (String key  :  keys){
//通过键  找值
//prop.get(key)
String value  = prop.getProperty(key);
        }
   }
}

将集合中的内容储存到文件

  • 从属性集文件prop.properties中取出数据,保存到集合中
    步骤如下
public class PropertiesDemo03 {
	public static void main(String[] args) throws IOException {
		//1,创建集合
		Properties prop = new Properties();
		// 2,创建流对象
		FileInputStream in = new FileInputStream("prop.properties");
//FileReader in = new FileReader("prop.properties");
		//3,把流所对应文件中的数据 读取到集合中
		prop.load(in);
		//4,关闭流
		in.close();
		//5,显示集合中的数据
		System.out.println(prop);
		
	}
}

序列化流与反序列化流

用于从流中读取对象的操作流 Objectinputstream 称为 反序列化流

用于向刘中写入对象的操作流ObjectOutputstream

发布了43 篇原创文章 · 获赞 6 · 访问量 1556

猜你喜欢

转载自blog.csdn.net/weixin_43729631/article/details/86544895
今日推荐