IO流(三)字符流(读写字符,并可以设置字符类型比如UTF-8)

字符输出 流  OutputStreamWriter,也是基于字节流FileOutputStream

  • BufferedWriter  好处:  newLine()  写入一个行分隔符。 
    • FileWriter 写文件,可追加而不是重新覆盖 专门针对文件写入,可以追加内容append()(普通输出流写文件是删除文件原本内容重新从头开始写) 
void writeFile() throws IOException {
		File file = new File("f://d.txt");
		FileOutputStream fos = new FileOutputStream(file);
		OutputStreamWriter osw = new OutputStreamWriter(fos);//

		osw.write("hello,i am cuijiao");
		osw.write(99);

		osw.close();
		fos.close();
	}

字符输出 流  InputStreamReader,也是基于字节流FileInputStream

  • BufferedReader 好处 readLine()  读取一个文本行。 
    • FileReader 专门针对文件读(通常来讲,流不仅针对文件,网络间的数据传输也是通过流) 
void readFile() throws IOException {
		File file = new File("f://d.txt");
		if (!file.exists()) {
			return;
		}
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis);
		int i = -1;

		
		while ((i = isr.read()) != -1) {
			System.out.print((char) i);
		}

		isr.close();
		fis.close();
	}

同样的,字符流读取文件放到字符数组作为缓冲区去读,速度更快。char[] buf = new char[1024];

void readFilebyArray() throws IOException {
		File file = new File("f://d.txt");
		if (!file.exists()) {
			return;
		}

		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis);// 字符流

		char[] buf = new char[1024];
		int len = -1;

		// 准备拷贝
		long begin = System.currentTimeMillis();
		while ((len = isr.read(buf)) != -1) {
			System.out.print(new String(buf, 0, len));
		}
		// 拷贝结束
		long end = System.currentTimeMillis();
		System.out.println("花费时间:");
		System.out.println(end - begin);
		// 先关高级流
		isr.close();

		fis.close();

	}
  •  附:标准输入输出:System.in  读入
  •                                               out  输出
  •                                                err  输出错误信息(表现为红色字体)

RandomAccessFile  既不属于输入也不属于输出,就是一个普通类,支持对文件读写操作

seek(.lenth)追加

上一篇文章jiang 到两种复制文件的方式:字节流和用缓冲流,现在介绍一种更快的方式:文件通道(属于NIO)


	void copyfilebyFileChannel(File src, File target) throws IOException {
		FileInputStream fis = new FileInputStream(src);
		FileOutputStream fos = new FileOutputStream(target);
		FileChannel in = fis.getChannel();// 获取文件通道
		FileChannel out = fos.getChannel();

		// 准备拷贝
		long begin = System.currentTimeMillis();

		in.transferTo(0, in.size(), out);// 将通道关联并传输文件

		// 拷贝结束
		long end = System.currentTimeMillis();
		System.out.println("花费时间:");
		System.out.println(end - begin);
		
		out.close();
		in.close();
		fos.close();
		fis.close();
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章