码迷,mamicode.com
首页 > 编程语言 > 详细

Java学习之IO字节流

时间:2016-01-24 00:22:47      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

 字节流分为FileInputStream 和FileOutputStream

 1 package com.io;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 /**
 9  * 文件字节流的读取
10  * @author ganhang
11  *
12  */
13 public class FileInputStreamDemo {
14     public static void main(String[] args) {
15         File file=new File("1.txt");
16         try {
17             InputStream is=new FileInputStream(file);
18             byte [] b= new byte[10];
19             int len=-1;
20             StringBuilder sb=new StringBuilder();//存读取的数据
21             while((len=is.read(b))!=-1){
22                 sb.append(new String(b,0,len));
23             }
24             is.close();
25             System.out.println(sb);
26         } catch (FileNotFoundException e) {
27             e.printStackTrace();
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31         
32     }
33 }
 1 package com.io;
 2 
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 /**
 9  * 文件字节流的写入
10  * @author ganhang
11  *
12  */
13 public class FileOutputStreamDemo {
14     public static void main(String[] args) {
15         File file = new File("1.txt");
16         if (!file.exists()) {
17             try {
18                 file.createNewFile();//没有则创建文件
19             } catch (IOException e) {
20                 e.printStackTrace();
21             }
22         } else {
23             try {
24                 OutputStream fos = new FileOutputStream(file, true);//文件末尾添加,不是覆盖
25                 byte[] info = "hello,world".getBytes();
26                 fos.write(info);
27                 fos.close();
28                 System.out.println("写入成功!");
29             } catch (FileNotFoundException e) {
30                 e.printStackTrace();
31             } catch (IOException e) {
32                 e.printStackTrace();
33             }
34         }
35     }
36 }

 

Java学习之IO字节流

标签:

原文地址:http://www.cnblogs.com/ganhang-acm/p/5154293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!