打印流是输出信息最方便的类,注意包含字节打印流PrintStream和字符打印流:PrintWriter。打印流提供了非常方便的打印功能,
可以打印任何类型的数据信息,例如:小数,整数,字符串。
import java.io.*;
import java.lang.Math;
public class Test{
static void copy() throws FileNotFoundException {
/** @知识点1:
* System.in; 标准的输入流: 默认是键盘录入
* System.out; 标准的输出流: 默认是输出到控制台。
* System.setIn(InputStream in); 改变来源。
* System.setOut(PrintStream ps);
*/
System.setIn(new FileInputStream("C:\\Users\\Lenovo\\Desktop\\2.txt"));
System.setOut(new PrintStream("C:\\Users\\Lenovo\\Desktop\\2(copy).txt"));
try{
//使用PrintStream类,将异常信息打印在外部文件当中。
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
/**知识点2:
* 二: PrintStream: 打印流:
* 特点:
* (1)能够打印基本数据类型的值。
* (2)PrintStream 永远不会抛出 IOException;
* (3)写入 byte 数组之后自动调用 flush 方法。自动刷新。
* (4)println(); 提供了换行的方法。
* 构造器:
* PrintStream(File file)
* 创建具有指定文件且不带自动行刷新的新打印流。
* PrintStream(File file, String csn)
* PrintStream(OutputStream out) ;
* PrintStream(OutputStream out, boolean autoFlush) ;自动刷新。
* PrintStream(String fileName)
*/
PrintStream ps = System.out;
String line = null;
while((line = bufr.readLine()) != null && !"over".equalsIgnoreCase(line)) {
ps.println(line.toUpperCase());
}
bufr.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}
}
static void save() throws FileNotFoundException {
PrintStream ps = null ; // 声明打印流对象
// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
// 通过定义的构造方法可以发现,有一个构造方法可以直接接收OutputStream类的实例,与OutputStream相比起来,PrintStream可以更方便的输出数据,
// 相当于把OutputStream类重新包装了一下,使之输出更方便
ps = new PrintStream(new FileOutputStream(new File("C:\\Users\\Lenovo\\Desktop" + File.separator + "test.txt"))) ;
ps.print("hello ") ;
ps.println("world!!!") ;
ps.print("1 + 1 = " + 2) ;
ps.printf("\n%.2f",Math.PI);
ps.close() ;
}
public static void main(String args[]) throws FileNotFoundException {
save();
copy();
}
}
参考资料:
JAVA的IO流:打印流
java打印流总结