Java内存操作流、格式化输出、打印流

1.内存操作流

1.1 内存流概念

目录在之前所有的操作都是针对于文件进行的IO处理。除了文件之外,IO的操作也可以发生在内存之中,这种流称之为内存操作流。文件流的操作里面一定会产生一个文件数据(不管最后这个文件数据是否被保留)。
如果现在需求是:需要进行IO处理,但是又不希望产生文件。这种情况下就可以使用内存作为操作终端。
内存流也分为两类:

  1. 字节内存流:ByteArrayInputStream、ByteArrayOutputStream
  2. 字符内存流: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);
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值