字节、字符转换流
OutputStreramWriter:将输出的字节流转化为字符流
InputStreamReader:将输入的字节流转换为字符流
但是不管如何操作,最后都是以字节的形式保存在文件中的。
将字节输出流转化为字符输出流
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class IOOperation {
public static void main(String[] args) throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
Writer out = new OutputStreamWriter(new FileOutputStream(f));
out.write("hello!");
out.close();
}
}
运行结果:文件中写入hello!
将字节输入流变为字符输入流
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class IOOperation {
public static void main(String[] args) throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
Reader in = new InputStreamReader(new FileInputStream(f));
char[] charArr = new char[1024];
int len = in.read(charArr);
in.close();
System.out.println(new String(charArr, 0, len));
}
}
执行结果:hello