码迷,mamicode.com
首页 > 其他好文 > 详细

reader,字符流

时间:2016-11-18 23:14:13      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:code   print   注意   基础   style   自动   file   资源   static   

1、

public class Demo1 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\a.txt");
        FileReader fileReader = new FileReader(file);
        int content = 0;
        while ((content=fileReader.read())!=-1) {   
            System.out.print((char)content);
        }
        fileReader.close();
    }
}

2、利用数组

public class Demo1 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\a.txt");
        FileReader fileReader = new FileReader(file);
        int length = 0;
        char[] buf=new char[1024];
        while ((length=fileReader.read(buf))!=-1) {
            System.out.print(new String(buf,0,length));
        }
        fileReader.close();
    }
}

3、写出数据

/**
 * 步骤:
 * 1、找到目标文件
 * 2、建立输出通道
 * 3、写出数据
 * 4、关闭资源
 * 
 * FileWriter要注意的事项:
 * 1、使用FileWriter写数据的时候,FileWriter内部是维护了一个1024个字符的数组,写入数据的时候会先写到它内部维护
 *   的字符数组中,如果需要把数据写到硬盘上,需要调用Flush或者close方法,或者填满了数组。
 * 2、使用FileWriter写数据的时候,如果目标文件不存在,那么会自动创建目标文件。
 * 3、使用FileWriter写数据的时候,如果目标文件已经存在了,那么默认情况下会先清空文件中的数据,然后在写入数据,如果
 *    要在原来的基础上追加数据,则New FileWriter(file,true).
 */
public class Demo2 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\b.txt");
        FileWriter fileWriter = new FileWriter(file);
        String dataString = "努力学习!!";
        fileWriter.write(dataString);
        fileWriter.close();
    }
}

 

reader,字符流

标签:code   print   注意   基础   style   自动   file   资源   static   

原文地址:http://www.cnblogs.com/h-g-f-s123/p/6079113.html

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