ファイルの読み書き

2013年6月3日月曜日

Android

t f B! P L

読みその1(stream)

try {
 InputStream is = openFileInput("filename");
 BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 String line;
 while ((line = reader.readLine()) != null) {
  //処理
 }
 reader.close();
} catch(IOException e) {
 e.printStackTrace();
}

読みその2(bytes)

byte[] contents = null;
try {
 FileInputStream is = openFileInput("filename");
 contents = new byte[is.available()];
 is.read(contents);
 is.close();
} catch(IOException e) {
 e.printStackTrace();
}

書きその1(stream)

String s = "I want to write this message.";
try {
 OutputStream os = openFileOutput("filename",MODE_PRIVATE);
 PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
 writer.append(s);
 writer.close();
} catch(IOException e) {
 e.printStackTrace();
}

書きその2(bytes)

String s = "I want to write this message.";
try {
 FileOutputStream os = openFileOutput("filename",MODE_PRIVATE);
 out.write(s.getBytes());
 out.close();
} catch(IOException e) {
 e.printStackTrace();
}

QooQ