标准的输入输出流与转换流

标准的输入输出流与转换流

标准的输入输出流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.*;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) {
//标准输入流,编译类型为InputStream,而运行类型为BufferInputStream
System.out.println(System.in.getClass());

//标准输出流,编译类型为PrintStream,运行类型为PrintStream
System.out.println(System.out.getClass());

}
}

image-20220703173029581

转换流

可以将字节流转换为字符流,解决文件乱码的问题,默认情况下按照utf-8编码进行阅读的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) throws IOException {
String filePath="D:\\文件下载\\hello.txt";
BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath));
String line;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
bufferedReader.close();
}
}

image-20220703173043100

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) throws IOException {
String filePath="D:\\文件下载\\hello.txt";
//首先利用放入到InputStreamReader可以设置编码格式的构造函数,构造成这样
InputStreamReader inputStreamReader=new InputStreamReader(new FileInputStream(filePath),"gbk");
//然后在使用BufferedReader去重新接受
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String line;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
bufferedReader.close();
}
}

image-20220703173051761

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
* @author zss
*/
public class Test {
public static void main(String[] args) throws IOException {
String filePath="D:\\文件下载\\hello.txt";
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8);
BufferedWriter bufferedWriter=new BufferedWriter(outputStreamWriter);
bufferedWriter.write("你好啊");
bufferedWriter.close();
}
}