【java】打印流的基本实现及java.io.PrintStream、java.io.PrintWriter示例

时间:2023-03-08 19:26:39
【java】打印流的基本实现及java.io.PrintStream、java.io.PrintWriter示例
 package 打印流;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; class MyPrint{
private OutputStream out;
public MyPrint(OutputStream out){
this.out=out;
}
public void print(String str) throws IOException{
out.write(str.getBytes());
}
public void print(int i) throws IOException{
print(String.valueOf(i));
}
public void print(byte b) throws IOException{
print(String.valueOf(b));
}
public void print(short s) throws IOException{
print(String.valueOf(s));
}
public void print(long l) throws IOException{
print(String.valueOf(l));
}
public void print(float f) throws IOException{
print(String.valueOf(f));
}
public void print(double d) throws IOException{
print(String.valueOf(d));
}
public void print(boolean b) throws Exception{
print(String.valueOf(b));
}
public void print(char c) throws IOException{
print(String.valueOf(c));
}
public void close() throws IOException{
out.close();
}
}
public class TestPrint {
public static void main(String[] args) throws IOException {
MyPrint myPrint=new MyPrint(new FileOutputStream(new File("D:"+File.separator+"testA.txt")));
myPrint.print(8.8);
myPrint.print('a');
myPrint.close();
}
}

MyPrint

 package 打印流;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter; public class TestPrintStream {
public static void main(String[] args) throws IOException {
PrintStream printStream=new PrintStream(new FileOutputStream(new File("D:"+File.separator+"Test.txt")));
printStream.print(true);
printStream.println("abc中国人");
printStream.close(); PrintWriter printWriter=new PrintWriter(new FileWriter(new File("D:"+File.separator+"testA.txt")));
printWriter.print(false);
printWriter.println(89898.23);
printWriter.close();
}
}

PrintStream和PrintWriter

 package 打印流;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream; public class TestPrintStream {
public static void main(String[] args) throws IOException {
String name = "张三";
int age = 20;
float height = 1.7586f;
PrintStream printStream = new PrintStream(new FileOutputStream(
new File("D:" + File.separator + "Test.txt")));
printStream.printf("姓名:%s,年龄:%d,身高:%1.2f", name, age, height);
printStream.close(); // PrintWriter printWriter=new PrintWriter(new FileWriter(new
// File("D:"+File.separator+"testA.txt")));
// printWriter.close();
System.out.println(String.format("姓名:%s,年龄:%d,身高:%1.2f", name, age,
height));
}
}

格式化输出

输出操作建议用打印流,而不是输出流