Published using Google Docs
Reading and Writing Files in Java for Android
Updated automatically every 5 minutes

Reading and Writing Files in Java for Android

โดย

เอกชัย บุญทิสา[1]

เขียน 2 กุมภาพันธ์ 2562  (อัพเดต ...)

บทความนี้กล่าวถึงการอ่าน-เขียนไฟล์ด้วยภาษา Java โดยอ่านเขียนที่ละบรรทัด (read & write by line)

สารบัญ

Reading Files in Java        1

Writing Files in Java        2

Reading Files in Java

BufferedReader br = null;
FileReader fr =
null;
File folderx =
new File(Environment.getExternalStorageDirectory() +
          File.separator +
"Zam_Gen");
boolean success = true;
if (!folderx.exists()) {
   success = folderx.mkdirs();
// Create Zam_Gen folder , if does not exist
}
if (success) {
   
// Do something on success
   File myFile =
new File(folderx, "data.txt");//.PES
   
if (!myFile.exists()){
       myFile.createNewFile();
// Create data.txt file , if does not exist
       Toast.makeText(
this,"No data file, Created a data file.",Toast.LENGTH_SHORT).show();
   }
else{
       fr =
new FileReader(myFile);
       br =
new BufferedReader(fr);

       String sCurrentLine;

       
boolean boolNull =  true;

       
while ((sCurrentLine = br.readLine()) != null) {
           list.add(sCurrentLine);
//read by line and use it, this add it to ArrayList
           boolNull =  
false;
       }

       br.close();
       fr.close();
       
if (boolNull) {
           Toast.makeText(
this, "Load OK!,BUT NO DATA", Toast.LENGTH_SHORT).show();
       }
else{
           Toast.makeText(
this, "Load data OK!", Toast.LENGTH_SHORT).show();
       }
   }
}
}
catch (Exception e){}

Writing Files in Java

BufferedWriter bw = null;
FileWriter fw =
null;
try {
  File folder =
new File(Environment.getExternalStorageDirectory() +
                   File.separator +
"Zam_Gen");
 
boolean success = true;
 
if (!folder.exists()) {
     success = folder.mkdirs();
  }
 
if (success) {
     
// Do something on success
     File myFile =
new File(folder, "data.txt");//.PES

     fw =
new FileWriter(myFile, false); // true ... ie. write add , false ... ie override
     bw =
new BufferedWriter(fw);

     String string =
"";

     bw.write(string);

     bw.close();
     fw.close();
  }
}
catch (Exception e){

}


[1] นายเอกชัย บุญทิสา ครูผู้ช่วย โรงเรียนพิมายวิทยา อำเภอพิมาย จังหวัดนครราชสีมา