• java生成txt文件,读txt文件


    1.方法1

    public static void main(String[] args) {
            try {
                FileWriter fileWriter = new FileWriter("c:\Result.txt");
                String ss = "cName	cCode		createDate
    ";
                ss += "dbc券		111188		2017-05-14
    ";
                ss += "zc券		111199		2017-05-14
    ";
                fileWriter.write(ss);
                fileWriter.flush();
                fileWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(">>>>>>>>>>>>>>>>>>write end");
    
            try {
                FileReader fileReader = new FileReader("c:\Result.txt");
                BufferedReader br = new BufferedReader(fileReader);
                String s;
                while ((s = br.readLine()) != null) {
                    System.out.println(s);
                }
                fileReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        System.out.println(">>>>>>>>>>>>>>>>>>read end");
    }

    2.方法2

    public static void main(String[] args) {
            File f = new File("c:\temp.txt");
            OutputStream out = null;
            try{
                out = new FileOutputStream(f);
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }
            
            String ss = "cName		cCode		createDate
    ";
            ss += "dbc券		111188		2017-05-14
    ";
            ss += "zc券		111199		2017-05-14
    ";
            // 将字符串转成字节数组
            byte b[] = ss.getBytes();
            try
            {
                // 将byte数组写入到文件之中
                out.write(b);
                out.close();
            }catch (IOException e1){
                e1.printStackTrace();
            }
            
            
            System.out.println("write end>>>>>>>>>>>");
            // 以下为读文件操作
            InputStream in = null;
            try{
                in = new FileInputStream(f);
            }catch (FileNotFoundException e3){
                e3.printStackTrace();
            }
    
            // 开辟一个空间用于接收文件读进来的数据
            byte b1[] = new byte[1024];
            int i = 0;
            try{
                // 将b1的引用传递到read()方法之中,同时此方法返回读入数据的个数
                i = in.read(b1);
                in.close();
            }catch (IOException e4){
                e4.printStackTrace();
            }
    
            // 将byte数组转换为字符串输出
            System.out.println(new String(b1, 0, i));
            System.out.println("read end>>>>>>>>>>>");
    
        }    
  • 相关阅读:
    poj 最长公共子序列 1458 记忆式搜索
    选择排序
    直接 插入排序
    直接插入排序
    洛谷-P3389-高斯消元
    经济中的哪些概念
    uva-622-dp
    UVA-607-DP
    转转---面试题
    Linux事件驱动IO中select vs epoll
  • 原文地址:https://www.cnblogs.com/simpledev/p/6852787.html
Copyright © 2020-2023  润新知