IO 詳解 ,input與output 是以內存作爲參考

先上兩個demo:

第一個是直接寫文件

 public static boolean writeFileContent(File file,String context,boolean append) throws IOException{
        FileOutputStream fos  = null;
        OutputStreamWriter pw = null;
        boolean result=false;
        try {
            fos = new FileOutputStream(file,append);
            pw = new OutputStreamWriter(fos, "UTF-8");
            pw.write(context);
            pw.flush();
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //不要忘記關閉
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        return result;
    }


第二個,先讀取再寫入:


  public static boolean writeFileContent(String p,String fileName,String newstr) throws IOException{
        Boolean bool = false;
        String filein = newstr;//新寫入的行,換行
        String temp  = "";
        String filepath=p+"/"+fileName+".txt";
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路徑(包括文件名稱)
            //將文件讀入輸入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            
            //文件原有內容
            for(int i=0;(temp =br.readLine())!=null;i++){
                buffer.append(temp);
                // 行與行之間的分隔符 相當於“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);
            
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            //不要忘記關閉
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }



博客參考:

http://blog.csdn.net/u010041075/article/details/49007731


發佈了32 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章