文件读写

判断文件是否存在

File file = new File(string filePath);
if (!file.exists()) {
    label2.setText("文件不存在");
    return;
}

判断文件编码格式

借助第三方库cpDetector


    public void getCodeType(String filePath) {
        try {
            File file = new File(filePath);

            // 获取原始文件编码
            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
            detector.add(JChardetFacade.getInstance());
            Charset charset = null;
            //charset.name()就是编码
            charset = detector.detectCodepage(file.toURL());

            if (charset != null) {
                // 使用源文件的编码,读取文件
                InputStreamReader bufRead = new InputStreamReader(new FileInputStream(file), charset.name());
                StringBuilder sb = new StringBuilder();
                char[] buffer = new char[2048];
                int len = 0;
                while ((len = bufRead.read(buffer, 0, 2048)) > 0) {
                    sb.append(buffer, 0, len);
                }
                String text = sb.toString();
                bufRead.close();
                // 使用UTF-8编码写入文件
                BufferedWriter bufWriter = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
                bufWriter.write(text);
                bufWriter.flush();
                bufWriter.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

读文件

FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//已指定编码打开文件
InputStreamReader read = new InputStreamReader (new FileInputStream(file),"UTF-8");   
BufferedReader bufferedReader=new BufferedReader(read);   

// 操作完成后关闭
bufferedReader.close();
read.close();

写文件

// 写,new FileWriter(file,true)为添加
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(sb.toString());
bufferedWriter.close();

results matching ""

    No results matching ""