首页 > 其他 > 详细

java io读写文件

时间:2014-03-03 16:16:32      阅读:461      评论:0      收藏:0      [点我收藏+]

java io读写文件
相关阅读:http://www.cnblogs.com/wing011203/archive/2013/05/03/3056535.html

 

 

bubuko.com,布布扣
public class DemoIO {

    public static byte[] readForInputStream(File file) throws IOException{
        InputStream in = new FileInputStream(file);  
        byte b[]=new byte[(int)file.length()];     //创建合适文件大小的数组   
        int len = 0;  
        int temp=0; //所有读取的内容都使用temp接收 
         while((temp=in.read())!=-1){//当没有读取完时,继续读取   
             b[len]=(byte)temp;  
             len++;  
         }
         in.close();  
         return b;  
    }
    
    public static void writeForOutputStream(File file) throws IOException {
        String content = "这是一段感人肺腑的文字";
        FileOutputStream fop = new FileOutputStream(file,true);//第二个参数ture:表示在内容中追加
        // 判断文件是否存在
        if (!file.exists()) {
            file.createNewFile();
        }
        byte[] contentInBytes = content.getBytes();
        fop.write(contentInBytes);
        fop.flush();
        fop.close();
        System.out.println("--------write success-------------");
    }
    
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
         
        writeForOutputStream(new File("e:/testio.txt"));
        
        byte[] b = readForInputStream(new File("e:/testio.txt"));
        System.out.println(new String(b, 0, b.length));
    }
}
bubuko.com,布布扣

java io读写文件,布布扣,bubuko.com

java io读写文件

原文:http://www.cnblogs.com/gavinYang/p/3577251.html

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