zoukankan      html  css  js  c++  java
  • 字符流例子

    【例子1】向文件中写入数据

    现在我们使用字符流

    
    /**  
     * 字符流  
     * 写入数据  
     */
    
    import java.io.*;
    
    class hello{
    
        public static void main(String[] args) throws IOException {
    
            String fileName="D:"+File.separator+"hello.txt";
    
            File f=new File(fileName);
    
            Writer out =new FileWriter(f);
    
            String str="hello";
    
            out.write(str);
    
            out.close();
    
        }
    
    }
    

    当你打开hello。txt的时候,会看到hello

    其实这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。

    当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:

    
    Writer out =new FileWriter(f,true);
    

    这样,当你运行程序的时候,会发现文件内容变为:

    
    hellohello如果想在文件中换行的话,需要使用“
    ”
    

    比如将str变为String str=" hello";

    这样文件追加的str的内容就会换行了。

    【例子2】从文件中读内容:

    
    /**  
     * 字符流   
     * 从文件中读出内容  
     */
    
    import java.io.*;
    
    class hello{
    
        public static void main(String[] args) throws IOException {
    
            String fileName="D:"+File.separator+"hello.txt";
    
            File f=new File(fileName);
    
            char[] ch=new char[100];
    
            Reader read=new FileReader(f);
    
            int count=read.read(ch);
    
            read.close();
    
            System.out.println("读入的长度为:"+count);
    
            System.out.println("内容为"+new String(ch,0,count));
    
        }
    
    }
    

    【运行结果】:

    
    读入的长度为:17
    
    内容为hellohello
    
    hello
    

    当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。

    
    /**  
     * 字符流   
     * 从文件中读出内容   
     */
    
    import java.io.*;
    
    class hello{
    
        public static void main(String[] args) throws IOException {
    
            String fileName="D:"+File.separator+"hello.txt";
    
            File f=new File(fileName);
    
            char[] ch=new char[100];
    
            Reader read=new FileReader(f);
    
            int temp=0;
    
            int count=0;
    
            while((temp=read.read())!=(-1)){
    
                ch[count++]=(char)temp;
    
            }
    
            read.close();
    
            System.out.println("内容为"+new String(ch,0,count));
    
        }
    
    }
    

    【运行结果】:

    
    内容为hellohello
    
    hello
  • 相关阅读:
    titlebar和actionbar上的按钮设置
    Android 实现闹钟功能
    关于禁止ViewPager预加载问题【转】
    RabbitMQ基础概念详细介绍
    Android 使用Android Studio + Gradle 或 命令行 进行apk签名打包
    Android4.0的Alertdialog对话框,设置点击其他位置不消失
    android MediaCodec 音频编解码的实现——转码
    一个android的各种控件库
    golang的验证码相关的库
    android studio提示unable to run mksdcard sdk
  • 原文地址:https://www.cnblogs.com/yuyu666/p/9733900.html
Copyright © 2011-2022 走看看