一、InputStream/OutputStream 和 Reader/Writer
辨析:
InputStream/OutputStream:1)抽象类;2)面向字节 形式的I/O操作 (8位字节流)。
Reader/Writer:1)抽象类;2)面向字符的I/O操作(16位的Unicode字符)。
InputStreamReader:可以将InputStream转换为 Reader;
OutputStreamWriter:可以将OutputStream转换为Writer;
注:图中细箭头标识实现接口,粗箭头标识继承父类。
示例代码:
class="java" name="code">
package javaio01;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* 使用 字符流和字节流两种方式,读取文本显示出来,并保存到指定的文件中;
* */
public class ReaderTest {
public static void main(String[] args) {
//methodBytes("a.txt");
methodString("a.txt");
}
/**
* First:字节流
* */
public static void methodBytes(String position) {
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(position);
int n = 1024;
byte inbuffer[] = new byte[n];
StringBuffer filecontent = new StringBuffer();
while(fileIn.read(inbuffer,0,n) != -1)
{
filecontent.append(new String(inbuffer));
}
System.out.println("字节流读取文件内容:\n"+filecontent.toString());
fileIn.close();//关闭输入流 释放资源
//字节流读取转为字符流读取
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(position)));
String str = null;
StringBuffer strbf = new StringBuffer("");
while((str = br.readLine()) != null)
{
strbf.append(str);
}
br.close();
System.out.println("\n字节流读取转为字符流读取:\n"+strbf.toString());
//写入文件b中
FileOutputStream os = new FileOutputStream("b.txt");
//写入输出流
os.write(filecontent.toString().getBytes());
//关闭输出流
os.close();
System.out.println("\n文件a的内容已经保存到b文件中去了!!!");
} catch (FileNotFoundException e) {
System.out.println("file not exit!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Second:字符流
* */
public static void methodString(String position) {
try {
/*1th*/
//BufferedReader br = new BufferedReader(new FileReader(new File("a.tx")));
/*2th*/
//FileReader fr = new FileReader(position);
//BufferedReader br = new BufferedReader(new FileReader("a.tx"));
/*3th : InputStreamReader:可以将InputStream转换为 Reader;*/
//将字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(position)));
String str = null;
StringBuffer filecontent = new StringBuffer();
while((str = br.readLine()) != null)
{
filecontent.append(str);
}
System.out.println("\n字节流读取文件内容:\n"+filecontent.toString());
br.close();//关闭输入流 释放资源
/*********************/
//将字符流 保存到文本中
BufferedWriter brt = new BufferedWriter(new FileWriter("b.txt"),1024);
brt.write(filecontent.toString());
brt.flush();
brt.close();
System.out.println("\n文件保存成功!!!\n");
/*********************/
PrintWriter pr = new PrintWriter(new FileOutputStream("aa.txt"));
pr.println("wwwwwwwwwwwwwwwww");
pr.flush();
pr.close();
} catch (FileNotFoundException e) {
System.out.println("file not exit!");
} catch (IOException e) {
e.printStackTrace();
}
}
}