您的位置:首页 > 编程语言 > Java开发

JAVA学习笔记(三十四)- 字节打印流 PrintStream

2015-03-28 08:24 141 查看

PrintStream字节打印流

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;

/*
* PrintStream字节打印流,输出数据更简单
*/
public class Test02 {
public static void main(String[] args) throws IOException {
test1();
}

// PrintStream
public static void test1() throws IOException {
// 定义一个文件字节输出流
FileOutputStream fos = new FileOutputStream("D:\\Java\\itany.txt");
// 定义一个字节打印流
PrintStream ps = new PrintStream(fos, true);
ps.println(25);
ps.println("哈哈");
ps.println("嘻嘻");
ps.print(true);
ps.print(13.5);
ps.append('a');
// ps.flush();
System.out.println("打印数据成功!");
ps.close();
}

//PrintWriter
public static void test2() throws IOException{
//定义一个文件字符输出流
FileWriter fw=new FileWriter("D:\\Java\\itany.txt");
//定义一个字符打印流
PrintWriter pw=new PrintWriter(fw);
//打印9*9乘法表
for(int i=1;i<=9;i++){
for(int j=1;j<=i;j++){
pw.print(i+"*"+j+"="+(i*j)+"\t");
}
pw.println();
}
pw.flush();
pw.close();
fw.close();

//读取数据
BufferedReader reader=new BufferedReader(new FileReader("D:\\Java\\itany.txt"));
String str=null;
while((str=reader.readLine())!=null){
System.out.println(str);
}
reader.close();

}

}


重定向标准输入输出

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

/*
* 重定向标准输入输出
*
* 默认输入设备为键盘
* 默认输出设备为显示器
*/
public class Test03 {
public static void main(String[] args) throws IOException {
//从默认输入设备获取一个字节的数据
/*int data=System.in.read();
System.out.println((char)data);*/

//将标准输入设备重定向到文件
FileInputStream fis=new FileInputStream("D:\\Java\\itany.txt");
System.setIn(fis);//重定向输入
//将标准转出设备重定向到PrintStream
PrintStream ps=new PrintStream("D:\\Java\\hello.txt");
System.setOut(ps);//重定向输出

//调用标准输入设备读取数据
int data=System.in.read();
while(data!=-1){
//调用标准输出设备打印数据
System.out.write((char)data);
//System.out.print((char)data);
data=System.in.read();
System.out.flush();

}
System.in.close();
System.out.close();
fis.close();
ps.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息