zoukankan      html  css  js  c++  java
  • JAVA-IO 字节流

    输入和输出流         

    InputStream抽象了应用程序读取数据的方式,即输入流(读)。

    OutputStream抽象了应用程序写出数据的方式,即输出流(写)。

    FileInputStream和FileOutputStream类的使用

     1.使用read()方法读取文件

    public static void main(String[] args) throws IOException {
    	FileInputStream  fis=new FileInputStream("D:\java\z.txt");
    	//读一个字节
    	int len=0;
    	while((len=fis.read())!=-1){
    		System.out.println((char)len);
    	}
    
    	
    	fis.close();
    }
    
    public static void main(String[] args) throws IOException {
    	FileInputStream  fis=new FileInputStream("D:\java\z.txt");
    	byte[] bytes=new byte 	[2];
    	int len=0;
    	while ((len=fis.read(bytes))!=-1) {
    		System.out.print(new String(bytes,0,len));
    	}
    	fis.close();
    }
    

    2 使用write()方法写入文件

    public static void main(String[] args) throws  IOException {
    	//明确地址
    	FileOutputStream fos= new FileOutputStream("D:\java\z.txt",true);
    	//写
    	//fos.write(100);
    	byte[] bytes={-66,-67,-68,-69};
    	fos.write("
    ".getBytes());
    	fos.write("你好".getBytes());
    	//释放资源
    	fos.close();
    }
    

     3异常处理

    public static void main(String[] args) {
    	FileOutputStream fos=null;
    	try {
    		fos = new FileOutputStream("D:\java\z.txt",true);
    		byte[] bytes={-66,-67,-68,-69};
    		fos.write("
    ".getBytes());
    		fos.write("你好".getBytes());
    	} catch (FileNotFoundException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}finally{
    		if(fos!=null){
    		try {
    			fos.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		}
    	}
    	
    	
    }
    
  • 相关阅读:
    CentOS 163 yum 源使用
    RedHat Enterprise Linux 5 安装TFTP服务器和NFS服务器
    Hadoop压缩SNAPPY算法安装
    linux 修改hostname 方法小结
    svnserver配置文件详解
    RedHat启动时sendmail启动慢的解决
    HBase 系统架构
    CentOS 域名解析 配置问题
    yum 安装 gcc
    Missing indirectly referenced artifact com.sun:tools:jar:1.5.0:system 错误
  • 原文地址:https://www.cnblogs.com/0826sw/p/12317139.html
Copyright © 2011-2022 走看看