2016-03-08 116 views
-3

我怎麼可以聽文件保存到SD卡時按下我有很多不同的按鈕和一個方法保存文件到SD卡

File file = new File(SDCardRoot,"/Download/Alnabi.pdf"); 

的按鈕的名稱,如果有人點擊該按鈕數量一個我想alnabi.pdf保存到SD卡,但如果我點擊第二個按鈕怎麼辦?我想要一種方法來改變文件名「alnabi.pdf」到另一個取決於哪個按鈕被點擊,謝謝。

+0

這不是有效的JavaScript語法。你在談論Java嗎? –

回答

0

您將不得不爲兩個按鈕提供不同的功能。但爲了保持代碼的可維護性,我建議重用代碼,這是所有/兩個按鈕(通過定義方法)通用的代碼。

的代碼可能看起來是這樣的:

button1.addActionListener(e -> saveFile("Alnabi.pdf")); // Java8-Syntax 
button2.addActionListener(e -> saveFile("AnotherOne.pdf")); 

與方法,具有共同的代碼:

public void saveFile(String variableFileName) { 
    File file = new File(SDCardRoot,"/Download/"+variableFileName); 
    ... 
} 
0

先寫一個檢查代碼,如果外部存儲空間可用於讀/寫操作 檢查用戶是否有權寫入外部存儲器的方法

public static boolean canWriteOnExternalStorage() { 
// get the state of your external storage 
String state = Environment.getExternalStorageState(); 
if (Environment.MEDIA_MOUNTED.equals(state)) { 
// if storage is mounted return true 
    Log.v(「sTag」, 「Yes, can write to external storage.」); 
    return true; 
} 
return false; 
} 

使用該代碼來保存文件

File sdcard = Environment.getExternalStorageDirectory(); 
File dir = new File(sdcard.getAbsolutePath() + 「/your-dir-name/」); 
dir.mkdir(); 
File file = new File(dir, 「My-File-Name.txt」); 
FileOutputStream os = outStream = new FileOutputStream(file); 
String data = 「This is the content of my file」; 
os.write(data.getBytes()); 
os.close(); 

需要以下權限

<uses-permission android:name=」android.permission.WRITE_EXTERNAL_STORAGE」 />