Androidアプリでのファイル読み書き

※ 今さらな内容のメモです。かなり古い内容を含んでいる可能性があります。

Androidアプリで設定データなどを保存するにはSharedPreferencesを用いるのがいちばん簡単である。
しかし、USB接続でデータファイルをPCとやりとりしたい場合もある。その場合、ファイルの読み書きは次のようにおこなう。

ディレクトリ作成

    // ストレージ直下に Hoge というディレクトリが無ければ作成
    String dirPath = Environment.getExternalStorageDirectory().getPath() + "/Hoge/";
    File dir = new File(dirPath);
    if(!dir.exists()){
        dir.mkdir();
    }

書き込み

    // Hoge/Piyo.txt というファイルに書き込み
    filePath = dirPath + "Piyo.txt";
    FileOutputStream fos = new FileOutputStream(filePath);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    BufferedWriter bw = new BufferedWriter(osw);
    
    bw.write("hogehogepiyopiyo");
    bw.newLine();

    bw.flush();
    bw.close();
    fos.getFD().sync(); // ストレージの同期
    fos.close();

読み出し

    // Hoge/Piyo.txt というファイルから読み出し
    filePath = dirPath + "Piyo.txt";
    FileInputStream fis = new FileInputStream (filePath);
    InputStreamReader isw = new InputStreamReader (fis);
    BufferedReader br = new BufferedReader(isr);

    String line = br.readLine();

    br.close();
    fis.close();