Java inputstream和outputstream使用详解
计算机在进行I/O时都是以流的形式来进行,Java中所有流的相关操作的类,都继承自以下四个抽象类。
输入流 输出流 字节流 InputStream OutputStream 字符流 Reader WriterInPutStream的实现
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream; public class TestFileInPutStream {public static void main(String[] args) {try {File file = new File('D:/test/testIO.java');// 如果文件存在,读取文件中的内容,并在控制台输出if (file.exists()) {InputStream in = new FileInputStream(file);int a = 0;while ((a = in.read()) != -1) {System.out.print((char) a);}in.close(); } else {// 如果文件不存在返回文件不存在System.out.println('文件不存在'); } } catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}
在D盘已经存在testIO文件如下:
将文件中的内容输出到控制台,结果如下:
OutPutStream的实现
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream; public class TestOutPutStream {private static InputStream in;private static OutputStream out;public static void main(String[] args) {try {in = new FileInputStream('D:/test/testIO.java');if(in == null){//原文件不存在System.out.println('原文件不存在');}else{//原文件存在,判断目标文件是否存在File file = new File('D:/test/testIOO.txt');if(!file.exists()){//目标文件不存在,创建目标文件file.getParentFile().mkdirs();file.createNewFile();}//将原文件内容读取到目标文件out = new FileOutputStream(file);int a = 0;while((a = in.read()) != -1){out.write(a);}}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//流关闭try {if(in != null){in.close();}if(out != null){out.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
D盘中原文件存在,在D盘中创建了目标文件
注意:在判断原文件是否存在时,直接判断字节流文件对象是否存在
到此这篇关于Java inputstream和outputstream使用详解的文章就介绍到这了,更多相关Java inputstream和outputstream内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
1. ThinkPHP5 通过ajax插入图片并实时显示(完整代码)2. ASP.NET MVC通过勾选checkbox更改select的内容3. Android实现图片自动切换功能(实例代码详解)4. jsp+mysql实现网页的分页查询5. javascript xml xsl取值及数据修改第1/2页6. 存储于xml中需要的HTML转义代码7. 使用AJAX(包含正则表达式)验证用户登录的步骤8. 解决Python paramiko 模块远程执行ssh 命令 nohup 不生效的问题9. JavaScript Tab菜单实现过程解析10. Python使用oslo.vmware管理ESXI虚拟机的示例参考
