文件读写操作-Java

来源:互联网 发布:scratch趣味编程实例 编辑:程序博客网 时间:2024/05/28 15:02

读文件

字符串读取

File file = new File("/path/test.txt");BufferedReader bufferedReader = new BufferedReader(new FileReader(file));String tempString = null;while ((tempString = bufferedReader.readLine()) != null) {    //todo:读写}bufferedReader.close();//关闭//InputStream in = new GZIPInputStream(new FileInputStream(fileName));读取压缩文件 

压缩文件读取

/** * @param fromFilePath 文件路径 * @return * @throws Exception */public static void segFile(String fromFilePath) throws Exception {    InputStream in = new GZIPInputStream(new FileInputStream(fromFilePath));    BufferedReader br = new BufferedReader(new InputStreamReader(in));    String temp = null;    while ((temp = br.readLine()) != null) {        System.out.println(temp);    }    in.close();    br.close();}

写文件

字符串写入

File file = new File("/path/test.txt");FileOutputStream out = new FileOutputStream(file); BufferedWriter br=new BufferedWriter(new OutputStreamWriter(out));br.write("test write");br.flush(); //刷缓存写到文件br.colse(); //关闭连接

自动获取文件编码

    /**     * 获取文件编码,其中ansi编码在windows debug模式下不支持     * @param fileName     * @return     */    public static String getFileEncode(String fileName) {            String charSet = "";           try {               FileInputStream fis = new FileInputStream(new File(fileName));               byte[] bf = new byte[3];               fis.read(bf);               fis.close();               if (bf[0] == -17 && bf[1] == -69 && bf[2] == -65) {                   charSet = "UTF-8";               } else if ((bf[0] == -1 && bf[1] == -2)) {                   charSet = "Unicode";               } else if ((bf[0] == -2 && bf[1] == -1)) {                   charSet = "Unicode big endian";               } else {                   charSet = "ANSI";               }           } catch (Exception e) {               e.printStackTrace();           }           return charSet;       }  
0 0
原创粉丝点击