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);
            }
    
        }
    }

     

  • 相关阅读:
    2.HTML案例二 头条页面
    1.HTML入门
    33.1.网络编程入门
    32.原子性
    【转】风控中的特征评价指标(一)——IV和WOE
    【转】Python调用C语言动态链接库
    基于蒙特卡洛树搜索(MCTS)的多维可加性指标的异常根因定位
    正则表达式全集
    基于ray的分布式机器学习(二)
    基于ray的分布式机器学习(一)
  • 原文地址:https://www.cnblogs.com/alexkn/p/4649651.html
Copyright © 2011-2022 走看看