JavaIO(输入输出)——字节流读写文件

mac2024-10-02  54

程序从输入流中读取数据

package 字节流; import java.io.*; public class Example01 { public static void main(String[] args) throws Exception { FileInputStream in=new FileInputStream("C:\\Users\\88304\\Desktop\\test.txt"); int b=0; while(true) { b=in.read(); if(b==-1) break; System.out.println(b); } in.close(); } }

向输出流中写入数据

package 字节流; import java.io.*; public class Example02 { public static void main(String[] args) throws Exception { FileOutputStream out=new FileOutputStream("C:\\Users\\88304\\Desktop\\example.txt"); String str="lixiang"; byte[] b=str.getBytes(); for(int i=0;i<b.length;i++) { out.write(b[i]); } out.close(); } }

package 字节流; import java.io.*; public class filecopy { public static void main(String[] args) throws Exception { FileInputStream in=new FileInputStream("C:\\Users\\88304\\Desktop\\新建文本文档.txt"); FileOutputStream out=new FileOutputStream("C:\\Users\\88304\\Desktop\\新建文本文档2.txt"); int len; long begintime=System.currentTimeMillis(); while((len=in.read())!=-1) { out.write(len); } long endtime=System.currentTimeMillis(); System.out.println("拷贝文件耗时"+(endtime-begintime)+"毫秒"); in.close(); out.close(); } } 以下代码生成了一个新文件 package 字节流; import java.io.*; public class filecopy { public static void main(String[] args) throws Exception { InputStream in=new FileInputStream("C:\\Users\\88304\\Desktop\\新建文本文档.txt"); OutputStream out=new FileOutputStream("C:\\Users\\88304\\Desktop\\li.txt"); int len; long begintime=System.currentTimeMillis(); while((len=in.read())!=-1) { out.write(len); } long endtime=System.currentTimeMillis(); System.out.println("拷贝文件耗时"+(endtime-begintime)+"毫秒"); in.close(); out.close(); } }

李响Superb 认证博客专家 机器学习 TensorFlow 图像处理 成为一名优秀的算法工程师⬆️ ,目前还在读软件工程,AI攻防、算法和深度学习方向,微博同名❤️ :李响Superb,(记得关注,有问题微博私信!)我们一起努力呀!
最新回复(0)