1.内存操作流
1.1 内存流概念
目录在之前所有的操作都是针对于文件进行的IO处理。除了文件之外,IO的操作也可以发生在内存之中,这种流称之为内存操作流。文件流的操作里面一定会产生一个文件数据(不管最后这个文件数据是否被保留)。
如果现在需求是:需要进行IO处理,但是又不希望产生文件。这种情况下就可以使用内存作为操作终端。
内存流也分为两类:
- 字节内存流:ByteArrayInputStream、ByteArrayOutputStream
- 字符内存流:CharArrayReader、CharArrayWriter
1.2 内存流操作
//通过内存流实现大小写转换
public class ByteArrayStream{
public static void main(String[] args) throws IOException {
String m = "mmm";
// 实例化InputStream类对象,实例化的时候需要将你操作的数据保存到内存之中
// 最终读取的就是你设置的内容。
InputStream input = new ByteArrayInputStream(m.getBytes());
OutputStream output = new ByteArrayOutputStream();
int temp = 0;
while ((temp = input.read()) != -1) {
output.write(Character.toUpperCase(temp));
}
// 直接输出output对象
System.out.println(output);
input.close();
output.close();
}
}
2.打印流
2.1利用系统提出的打印流
public class TestPrintf {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter p = new PrintWriter(new FileOutputStream(new File("F:/Java/Test1/p.txt")));
p.print("名字");
p.print("ywh");
p.print("nia");
p.println(123);
p.close();//最后结果在文件里面
}
}
打印流分为字节打印流:PrintStream、字符打印流:PrintWriter
2.2格式化输出
//输出到文件里
public class TestPrint {
public static void main(String[] args) throws Exception {
String name = "yuisama" ;
int age = 25 ;
double salary = 1.107 ;
PrintWriter printUtil = new PrintWriter(new FileOutputStream(new
File("/Users/yuisama/Desktop/test.txt"))) ;
printUtil.printf("姓名:%s,年龄:%d,工资:%1.2f", name,age,salary) ;
printUtil.close();
}
}
//输出到运行界面
public class TestPrint {
public static void main(String[] args) throws Exception {
String name = "yuisama" ;
int age = 25 ;
double salary = 1.1070000000001 ;
String str = String.format("姓名:%s,年龄:%d,工资:%1.2f", name,age,salary,
name,age,salary) ;
System.out.println(str);
}
}