文件的讀寫

讀數據:app

public static String txt2String(){
        File file = new File("G:/data/swf/data.txt");
        StringBuilder result = new StringBuilder();
        try{
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            BufferedReader br = new BufferedReader(isr);//構造一個BufferedReader類來讀取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次讀一行
                result.append(System.lineSeparator()+s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }

寫入數據:ui

public static void writeFile(String str) throws IOException {
        //寫入中文字符時解決中文亂碼問題
        FileOutputStream fos=new FileOutputStream(new File("G:/data/swf/data.txt"),true);
        OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter  bw=new BufferedWriter(osw);
        bw.write(str+",");

        //注意關閉的前後順序,先打開的後關閉,後打開的先關閉
        bw.close();
        osw.close();
        fos.close();
    }
相關文章
相關標籤/搜索