Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Read and write file di android
- -READING-
- pertama tentuin lokasi file yang kamu mau
- String file_location = "/sdcard/myid.txt";
- lalu panggil method file di android
- File maijangar = new File(file_location);
- untuk membaca file maka gunakan FIleInputStream
- String aBuffer = "";
- FileInputStream fIn = null;
- try {
- fIn = new FileInputStream(myFile);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Setela itu seperti biasa masukin ke BeufferdReader
- BufferedReader myReader = new BufferedReader(new InputStreamReader(
- fIn));
- dan dibaca untuk setiap barisnya
- String aDataRow = "";
- try {
- while ((aDataRow = myReader.readLine()) != null) {
- aBuffer += aDataRow;
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- dan Jangan lupa untuk di tutup
- try {
- myReader.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Log.d("readFile : ", aBuffer);
- return aBuffer;
- -===============================================================-
- Membuat File Baru
- tinggal create new File Aja pada kelas File
- try {
- myFile.createNewFile();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- -===============================================================-
- Membuang File
- tinggal panggil delete aja di kelas File
- myFile.delete()
- -===============================================================-
- -WRITING-
- yang di gunain yaitu FileOutputStream yang sebelumnya dimasukkan ke myFile tentunya
- FileOutputStream fOut = null;
- try {
- fOut = new FileOutputStream(myFile);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Nah setelah itu masukin teks dari dokumen yang ada pada FileOutputStream dimasukkan ke OutputStreamWriter, lalu di append berdasarkan teks yang diminta :
- OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
- try {
- myOutWriter.append(myText);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Jangan lupa di Tutup pastinya
- try {
- myOutWriter.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- fOut.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement