天天看點

關于Java流的方式将資料寫入到檔案中

參考:《第一行代碼》

Java部分還不是很熟,渣渣在努力

在安卓的資料存儲方式中有一招是檔案存儲,當然安卓内置有Context類的openFileOutput()方法将資料存儲到指定檔案中,有openFileInput()方法打開指定檔案。openFileOuput()方法傳回一個FileOutputStream對象,openFileInput()方法傳回一個FileInputStream對象,拿到這對象以後就可以使用java流的方式将資料寫入或讀出檔案了。

java流檔案寫入

openFileOutput()方法傳回FileOutputStream對象,再拿到OutputStreamWriter(中間橋梁)對象,再拿到BufferedWriter(緩沖)對象,再調用write()方法寫入,注意close(),

public void save(String inputText){
        FileOutputStream out=null;
        BufferedWriter writer=null;
        try {
            out=openFileOutput("data", MODE_PRIVATE);
            writer=new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
           

java流的檔案讀出(與寫入對應,為加深記憶,再寫一遍)

首先,openFileInput()拿到FileInputStream對象,再通過這個對象拿到InputStreamReader對象,再通過InputStreamReader對象拿到BufferedReader對象,進而調用readline()方法進行讀出,不要忘了close(),

public String  load(){
        FileInputStream inputStream=null;
        BufferedReader reader=null;
        StringBuilder contentBuilder=new StringBuilder();
        try {
            inputStream=openFileInput("data");
            reader=new BufferedReader(new InputStreamReader(inputStream));
            String line="";
            while((line=reader.readLine())!=null){
                contentBuilder.append(line);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return contentBuilder.toString();
    }