转换流其实听名字就不是很难理解
比如字节流转字符流
这里我就不再演示输出结果了,这一篇博客我没有验证我写的代码不过一般是没有多大问题的,就算有自己花点时间调试一下就好了,不要太懒。还有就是记得包含上指定的包,要不然肯定会报错的。
这里建议大家还是不要偷懒自己弄几个文件敲一下代码运行下。这里我们可能只会讲字节流转字符流,字符流转字节流其实根本就没必要转的,因为字节流直接就有一个getByte方法,直接就获得到二进制数据了,完全就没必要转化了。
/**
* 字节流转字符流
*/
public static void readConvertFile() {
InputStream is = null;
InputStreamReader isr = null;//字节输入流转字符输入流
BufferedReader br = null;
try {
is = new FileInputStream("C:\\Users\\HASEE\\Desktop"+File.separator +"物流系统.txt");
isr = new InputStreamReader(is,"utf-8");
br = new BufferedReader(isr);
String str = null;
StringBuilder sb = new StringBuilder();
//每次读取一行
while((str = br.readLine()) != null) {
sb.append(str);
//因为readLine()使用换行符来确认读取多少,所以不会读取换行符
sb.append("\n");
}
System.out.println(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {//关流的原则,最先开的最后关上
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 字节输出流转字符输出流
*/
public static void writeConvert() {
OutputStream os = null;
OutputStreamWriter osw = null;//字节输出流转字符输出流
BufferedWriter bw = null;
String str = "https://dl.pconline.com.cn/download/383493.html\r\n" +
" \r\n" +
" https://dl.pconline.com.cn/download/975557.html 建议选择\r\n" +
" \r\n" +
" https://dl.pconline.com.cn/download/827075.html 建议选择\r\n" +
" \r\n" +
" https://dl.pconline.com.cn/download/413902.html";
try {
os = new FileOutputStream("C:\\Users\\HASEE\\Desktop"+File.separator +"物流系统.txt",true);
osw = new OutputStreamWriter(os, "utf-8");
bw = new BufferedWriter(osw);
bw.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally { //关流的原则
if(bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}