1. 程式人生 > >將字串寫入檔案與讀取檔案

將字串寫入檔案與讀取檔案

 一,讀取檔案內容

            File file = new File(filePath);
            if(file.isFile() && file.exists()) {
                
                StringBuilder result = new StringBuilder();
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    result.append(lineTxt);
                }
                br.close();
            }
            
                

二,將字串寫入檔案

            File file = new File(filePath);
			if(!file.exists()){
				file.createNewFile();
			}
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
            //content為字串內容
	        osw.write(content);
	        osw.close();