1. PrintStream
学习:Java打印流PrintStream类详解_风有点大的博客-CSDN博客_printstream类
1.1向文件进行输出
PrintStream ps = new PrintStream("helloworld01.txt");
//输出目的地是一个文件,如果文件不存在,则会新建,若存在,则会修改里面的内容
//文件可以用绝对路径,像我这样子写是在这个项目相对应的文件中的
//绝对路径:D:\javaidea\work\classtest01\helloworld01.txt
1)继承父类的write方法写数据
//如果使用继承自父类的write方法写数据,那么查看数据的时候会查询编码表 97->a ps.write(97);
2)直接用print/println方法写数据
//如果使用自己特有的方法print/println方法写数据,写的数据原样输出 97->97 ps.println(97); ps.println(8.8); ps.println('a'); ps.println("HelloWorld"); ps.println(true);
//注意:要释放资源!!
ps.close();
3)改变输出语句的目的地:
//如果不进行改变,会在控制台输出 System.out.println("Hello World!"); System.setOut(ps);//把输出语句的目的地改变为打印流的目的地,不再打印到控制台,而是转到其它媒介 System.out.println("Hello World!");
//会输出到ps对应的文件中,如我这里是 helloworld01.txt中,并且之前的内容都被改写了,只剩下刚刚输出的"Hello World!"
4)输出一个对象时的输出结果,其中RedirectOut是一个java类,duixiang是一个包
public class class01 { public static void main(String[] args) { PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream("out.txt")); //将标准输出重定向到ps输出流 System.setOut(ps); //向标准输出输出一个字符串 System.out.println("普通字符串"); //向标准输出输出一个对象 System.out.println(new class01()); } catch (IOException ex) { ex.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }
对 new RedirectOut()修改成 new class01();其中,StreaAndFileSourceCode是一个包
2.FileInputStream
文件字符输出流,将文件的内容进行输出
FileInputStream fis = null; try { fis = new FileInputStream("RedirectIn.java"); //将标准输入重定向到fis输入流 System.setIn(fis); //使用System.in创建Scanner对象,用于获取标准输入 Scanner sc = new Scanner(System.in); //增加下面一行将只把回车作为分隔符 sc.useDelimiter("\n"); //判断是否还有下一个输入项 while (sc.hasNext()) { //输出输入项 System.out.println("键盘输入的内容是:" + sc.next()); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
控制台输出
标签:ps,java,输出,第六,System,ex,println,new,StreamAndFileSourceCode From: https://www.cnblogs.com/hmy22466/p/16815912.html