IO文件的读取与写入

文件读取:

private static String Data() {
        // 1.定义目标文件
        File srcFile = new File("D:/text.txt");
        // 2.创建一个流,指向目标文件
        InputStream is = null;
        StringBuffer data = new StringBuffer();
        try {
            is = new FileInputStream(srcFile);
            //3.创建一个用来存储读取数据的缓冲数组
            byte[]array = new byte[128];
            //4.循环往外流(count为每次读取数组中的有效字节总数)
            int count = is.read(array);
            // 5.循环打印
            
            while (count != -1) {
                // 将byte[] -》 String
                // 将byte数组读取到的有效字节转换成字符串
                String string = new String(array, 0, count);
                data.append(string);
                count = is.read(array);
            }
            System.out.println(data.toString());
            return data.toString();
        } catch (IOException e) {

        }
        //System.out.println(postResault);
        return null;
    }

文件写入:

public static void main(String[] args) throws IOException {
        File file = new File("D:\\EDI\\a.txt");
        FileOutputStream outputStream = new FileOutputStream(file,true);
        OutputStreamWriter stream = new OutputStreamWriter(outputStream);
        BufferedWriter writer = new BufferedWriter(stream);
        List<String> list = new ArrayList<String>();
        list.add("123466788");
        list.add("qwersa");
        String line = null;
        for (int i = 0; i < list.size(); i++) {
            line = list.get(i);
            writer.write("哈哈\r我真是一个大帅哥");
            writer.newLine();
        }
        writer.close();
        stream.close();
        outputStream.close();
    }

 

posted @ 2021-02-01 11:18  xiaobaitu88  阅读(109)  评论(0编辑  收藏  举报