java字节流

来源:互联网 发布:arp攻击软件 编辑:程序博客网 时间:2024/04/29 20:32

java字节流

public class HelloWorld {    public static void main(String[] args) {        // [1] 指定要保存的路径        String path = "d:\\aaa\\test.txt";        // 输出文件内容        outputFile(path, "nimeiadzcxzcdaaaaae");        // 获取文件内容        String result = inputFile(path);        System.out.println("读取结果" + result);        // 删除文件        //delFile(path);    }    /**     * 获取文件内容     * @param saveFilePath 要读取的文件位置     * @return 读取到的字符串     */    private static String inputFile(String saveFilePath) {        File file = new File(saveFilePath);        if(!file.exists()){            // 判断文件是否存在            return "文件不存在";        }        FileInputStream fis = null;        StringBuffer sb = null;        try {            //  创建一个输入流            fis = new FileInputStream(file);            sb = new StringBuffer();            int len = 0;            // 创建字节数组用于存放临时的数据            byte[] b = new byte[1024];            while (-1 != (len = fis.read(b))) {                String s = new String(b, 0, len);                sb.append(s);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fis != null) {                try {                    fis.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return sb.toString();    }    /**     * 输出内容到文件     * @param saveFilePath 文件的保存路径     * @param saveStr 要写入的字符串     */    private static void outputFile(String saveFilePath, String saveStr) {        // 根据指定路径创建文件        File file = new File(saveFilePath);        // 获取文件的父路径        File parentFile = file.getParentFile();        if(!parentFile.exists()){            // 路径不存在则创建路径            parentFile.mkdirs();        }        // 将字符串转换成字节数组        byte[] bytes = saveStr.getBytes();        FileOutputStream fos = null;        try {            fos = new FileOutputStream(file);            fos.write(bytes);            fos.flush();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public static void delFile(String saveFilePath){        File file = new File(saveFilePath);        // 删除文件        file.delete();    }}
0 0