Android開發中如何實現文件的讀寫?

Android開發中如何實現文件的讀寫?

//sd寫文件

public void write(View v){

//得到sd卡的狀態 狀態

String state=Environment.getExternalStorageState();

//如果sd卡是存在的 安裝好的 就把問價 寫到sd卡裡面

if(state.equals(Environment.MEDIA_MOUNTED)){

//文件 根目錄路徑 第二個參數是創建的文件名字

File file=new File(Environment.getExternalStorageDirectory(),"a.txt");

try {

//輸出流

FileOutputStream fos=new FileOutputStream(file);

fos.write("123ccc".getBytes());

fos.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

public void read(View v){

File file=new File(Environment.getExternalStorageDirectory(), "a.txt");

try {

FileInputStream fis=new FileInputStream(file);

//字符輸入流 轉換為字符流? 轉換流

//緩沖流 相當於村粗空間

BufferedReader br=new BufferedReader(new InputStreamReader(fis));

String readLine = br.readLine();

System.out.println(readLine);

} catch (Exception e) {

e.printStackTrace();

}

}

//讀取空間

public void readspace(View v){

//計算空間大小

TextView tv1=(TextView) findViewById(R.id.tv_neibu);

TextView tv2=(TextView) findViewById(R.id.tv_sd);

//先得到內部空間的總大小 目錄

File file=Environment.getDataDirectory();

long totalSpace = file.getTotalSpace();

//得到sd卡的總空間 mb 目錄 路徑

File sdfile=Environment.getExternalStorageDirectory();

long totalSpace2 = sdfile.getTotalSpace();

//這裡才是計算

String fileSize = Formatter.formatFileSize(this, totalSpace);

String sdSize = Formatter.formatFileSize(this, totalSpace2);

tv1.setText(fileSize);

tv2.setText(sdSize);

}

//掃描sd卡裡面的音樂

public void forsdcard(View v){

File file=Environment.getExternalStorageDirectory();

File[] filelist=file.listFiles(new FileFilter() {

@Override

public boolean accept(File pathname) {

if(pathname.isDirectory()){

return true;

}else if(pathname.getName().endsWith(".mp3")){

return true;

}

return false;

}

});

//遍歷出 所有返回true的文件

for (File file2 : filelist) {

}

}

You May Also Like