首页 > 其他 > 详细

IO流

时间:2017-02-14 17:57:36      阅读:205      评论:0      收藏:0      [点我收藏+]
package file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OutputStreamDemo {
/**
 *OutputStream
 * @param args
 * @throws Exception
 */
    public static void main(String[] args) throws Exception {
        /*
         * 执行时候如果文件不存在,则会在磁盘自动创建
         * 如果重复执行,会出现覆盖旧内容
         * 执行追加方法OutputStream ops = new FileOutputStream(file,true);
         * 只需要输出部分字节数据ops.write(data.getBytes(),0,5);
         */
        File file = new File("D:"+File.separator+"helloworld"+File.separator+"test.txt");
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            file.getParentFile().mkdir();
        }
        OutputStream ops = new FileOutputStream(file);
        String data = "helloworld.\r\n";
        ops.write(data.getBytes(),0,5);
        ops.close();
    }
    
}
package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.imageio.stream.FileImageInputStream;


/**
 * 在InputStreamDemo中定义了三个方法
 *     读取单个字节    public abstract int read() throws IOException;
 *         说明:每次执行read()方法都会读取一个字节,读取到最后没有的时候为-1
 * 
 *     读取多个字节    public int read(byte[] b) throws IOException;
 *         说明:如果现在要读取的数据小于byte的数据,这个时候read()方法返回的值int是  原数据的个数
 *             如果byte数组小于读取的长度,数据读完,int返回为-1
 * 
 *     读取指定多个字节     public int read(byte[] b,int off,int len) throws IOException;
 *     
 * 
 * @author Administrator
 *
 */
public class InputStreamDemo {
    
    public static void main(String[] args) throws Exception {
        
        File file = new File("D:"+File.separator+"helloworld"+File.separator+"test.txt");
        if(file.exists()) {
            InputStream is = new FileInputStream(file);
            byte[] data = new byte[1024];//假设一次性读取长度1024
            int len = is.read(data);//返回读取长度
            is.close();
            System.out.println("读取的数据是:【"+new String(data,0,len)+"】");
        }
        /*
         * 单个读取字节数据
         */
        File f = new File("D:"+File.separator+"helloworld"+File.separator+"test.txt");
        if(f.exists()) {
            InputStream is = new FileInputStream(f);
            byte[] data = new byte[1024];//假设一次性读取长度1024
            int foot = 0;//操作数组下标
            int temp = 0;
            while((temp = is.read()) != -1) {
                    data[foot++] = (byte) temp;
            }
            is.close();
            System.out.println("读取的数据是:【"+new String(data,0,foot)+"】");
        }
        
    }
    
}

 

IO流

原文:http://www.cnblogs.com/jietz0407-com/p/6398513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!