转载请注明出处:转换流InputStreamReader、OutputStreamWriter_Mr_Leixiansheng的博客-CSDN博客
1、InputStreamReader
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream fis = null;
BufferedReader reader = null;
try {
//设置读取位置
fis = new FileInputStream("d:\\text2.txt");
//转换流InputStreamReader
reader = new BufferedReader(new InputStreamReader(fis));
//缓存区
String str = "";
//读取数据
while((str = reader.readLine()) != null) {
System.out.println(str);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
//关闭流
reader.close();
fis.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
2、OutputStreamWriter
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileOutputStream fos = null;
BufferedWriter writer = null;
try {
String content = "要写出的内容";
fos = new FileOutputStream("d:\\text2.txt");
//转换流OutputStreamWriter
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(content);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
//关闭流
//注意关闭顺序,最后关闭FileOutputStream流,否则报错
writer.close();
fos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}