文件读取写入

183 阅读1分钟

参考链接

blog.csdn.net/atgeretg/ar…

static public String readFile(File file) {      

    try {
            FileInputStream fileInputStream = new FileInputStream(file);
            // 把每次读取的内容写入到内存中,然后从内存中获取
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            // 只要没读完,不断的读取
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 得到内存中写入的所有数据
            byte[] data = outputStream.toByteArray();
            fileInputStream.close();
            return new String(data);
            //return new String(data, "GBK");//以GBK(什么编码格式)方式转
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

文件写入 参考文章

www.cnblogs.com/daoqidelv/p…

从测试看,小文件差距都不大,所以小文件就用简单的读写就好了
FileOutputStream outputStream = null;
        try {
            File file = new File("d:test.txt");
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            String data = "Hello javaFile";
            outputStream.write(data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }