zoukankan      html  css  js  c++  java
  • Java读写文本文件

    1 字符输入(FileReader , char)

    import java.io.IOException;
    import java.io.FileReader;
    
    public class ep10_1 {
        public static void main(String[] args) throws IOException{
            //引用对象b
            FileReader b = new FileReader("/tmp/ep10_1.txt");
            //定义文本存储的reader空间
            char[] a = new char[1000];
            //将对象b的内容读入a中,返回字符数
            int num = b.read(a);
            //将字符a转换成str输出
            String str = new String(a,0,num);
            System.out.println("文件读取内容为:
    "+str);
         b.close();
    }
     }
    

    2 字符输出(FileWrite char)

    import java.io.FileWriter;
    import java.io.IOException;
    
    
    public class ep10_3 {
        public static void main(String[] args) {
            try{
                FileWriter a = new FileWriter("/tmp/wt.txt");
                for (int i=32;i<126;i++){
                    //char类型写入
                    a.write(i);
                }
                a.close();
            }catch (IOException e){}
        }
    }
    

     3 字符输入输出(BufferedReader,BufferedWriter,char) 

    import java.io.*;
    import java.nio.Buffer;
    
    public class ep10_4 {
        public static void main(String[] args) {
            String str = new String();
            try{
                //BufferedReader引用的类型为String,也就是说BufferedReader会把FileReader字符型的文本转换为String
            BufferedReader in = new BufferedReader(new FileReader("/tmp/ep10_1.txt"));
            BufferedWriter out = new BufferedWriter(new FileWriter("/tmp/ep10_4.txt"));
            while ((str=in.readLine())!=null) {
                System.out.println(str);
                out.write(str);
                out.newLine();
            }
            out.flush();
            in.close();
            out.close();
        }catch (IOException e){
                System.out.println("error contents:"+e);
            }
        }
    }

    4 字节的输入

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    
    public class ep10_5 {
        public static void main(String[] args) {
            try {
                byte[] bt = new byte[1000];
                FileInputStream ins = new FileInputStream("/tmp/ep10_1.txt");
                int num = ins.read(bt);
                String str = new String(bt,0,num);
                System.out.println("contents:
    "+str);
    
            }catch (IOException e){
                System.out.println("error:
    "+e);
            }
    
        }
    }

     

  • 相关阅读:
    Linux统计文件夹下所有文件的数量
    Linux查看文件最后几行的命令
    linux export将PATH环境变量误删了的解决办法
    laravel提示Mcrypt PHP extension required
    php(cli模式)执行文件传递参数
    shell判断文件是否存在,不存在则创建
    php获取Linux网卡信息
    使用iptraf,ifstat查看网络流量
    作用域
    头文件,库文件,重复包含
  • 原文地址:https://www.cnblogs.com/alexkn/p/4649651.html
Copyright © 2011-2022 走看看