Java基础23–打印流:PrintStream和PrintWriter
打印流:输出流
(1)PrintStream:
经典代表:System.out
Sysetm.err
@Test
public void test01(){
PrintStream out = System.out;
out.println("hello");
// out.print();//print没有无参方法
out.println();
}
new PrintStream(文件名)
new PrintStream(文件名,编码)
new PrintStream(另一个字节输出流)
@Test
public void test02() throws IOException{
PrintStream ps = new PrintStream("1.txt");
ps.println("hello");
ps.println("world");
ps.close();
}
1.txt文件里有打印内容
@Test
public void test03() throws IOException{
PrintStream ps = new PrintStream("d:/1.txt","GBK");
ps.println("中文");
ps.close();
}
不用inputStream,直接打印过来
@Test
public void test04() throws IOException{
//所有数据类型写出去,都是按照文本处理
PrintStream ps = new PrintStream("1.txt");
ps.println(12);
ps.println(true);
ps.println(new Goods("《从入门到放弃》", 99.99, 1000));
ps.close();
}
所有数据类型写出去,都是按照文本处理,比如12不是按int型存进去的,而是按1,2,的字符存进去的,其他也类似
(2)PrintWriter
Web阶段学习时,从服务器端往客户端返回消息时用到response,response.getWriter()可以返回PrintWriter对象。
即 Web服务器往客户端(例如:浏览器)返回html网页时,用的是PrintWriter对象的输出方法。
文本扫描仪:Scannner
System.in:默认情况下是从键盘输入的数据中扫描
Scanner:可以从你指定的文件、流中读取文本数据
Scanner:
@Test
public void test01(){
Scanner input = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = input.nextInt();
System.out.println("num = " + num);
input.close();
}
@Test
public void test02() throws FileNotFoundException{
Scanner input = new Scanner(new FileInputStream("1.txt"));//InputStream
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
input.close();
}
直接文件对象也行
@Test
public void test03() throws FileNotFoundException{
Scanner input = new Scanner(new File("1.txt"));//InputStream
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
input.close();
}
@Test
public void test04() throws FileNotFoundException{
Scanner input = new Scanner("1.txt");//InputStream
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
input.close();
}
@Test
public void test05() throws FileNotFoundException{
Scanner input = new Scanner(new File("d:/1.txt"),"GBK");//InputStream
while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}
input.close();
}
System类中的IO流
在Java层面是常量对象,但是可以通过C等底层语言进行修改,例如以下三个:
System.in:
System.out
System.err
观察System,发现inputStream为null,且为静态常量,不能改变
@Test
public void test01(){
PrintStream out = System.out;
System.out.println(out);
}
结果不为null,有对象
原因:静态常量out的赋值创建什么的不是通过java来的
可以看见system调用了一个静态方法,这个方法没有方法体,且是native修饰,说明底层是非java语言实现的,c语言(java中不能修改的静态常量,可以用非Java语言修改)
@Test
public void test02() throws FileNotFoundException{
System.setOut(new PrintStream("1.txt"));
System.out.println("aaaa");
System.out.println("bbb");
System.out.println("ccc");
System.out.println("ddd");
}
没往控制台打印,而是在1.txt文件里,说明不是System.out.println()都是往控制台打印,得看setOut()是往哪儿设置打印得,默认情况下往控制台打印,修改的话用setOut()方法,setOut()底层也是非java语言实现的