簡體   English   中英

使用Android存儲文件和文件夾

[英]Storing files and folders using android

我正在開發一個移動應用程序,將生成的值保存到文件中。 我已存儲在文件中,並且文件也保存在文件夾中。 但是從應用程序退出后,當我打開文件並嘗試讀取值時,它沒有讀取文件。 實際上,文件存儲在設備內存中,而不是外部設備中。 我已在清單文件中授予權限。

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

我在這里附上我的代碼。 請指導我我犯了什么錯誤。 //這里我存儲兩個數據

public void setData(String newData , String newTime , String fileName) throws JSONException {
  try { 
  //FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);  
  File sdcard = android.os.Environment.getExternalStorageDirectory();  
  File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");  
  directory.mkdirs();  
  File file = new File(directory,fileName);  
  FileOutputStream fou = new FileOutputStream(file , true);  
  OutputStreamWriter osw = new OutputStreamWriter(fou);  
  try {  
  osw.write(String.valueOf(newData));
  osw.append(',');
  osw.write(String.valueOf(newTime));
  osw.write(System.lineSeparator());
  osw.close();  
  } catch (IOException e) {  
  // TODO Auto-generated catch block  
  e.printStackTrace();  
  }  
  } catch (FileNotFoundException e) {  
  // TODO Auto-generated catch block  
  e.printStackTrace();  
  }  
  }

//這里我正在讀取保存在移動設備中的文件內容

  @TargetApi(Build.VERSION_CODES.KITKAT)
  @JavascriptInterface
  public String ReadFile(String fileName)
  {
  String content;
  ArrayList<String> arr = new ArrayList<String>();
  //int linenumber = 0;
  File sdcard = android.os.Environment.getExternalStorageDirectory();  
  File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");  
  //File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
  //File f = new File("");
  Log.d(TAG, "acrd checking called");
  System.out.println(sdcard.getAbsolutePath());
  File file = new File(directory,fileName);  
  try (InputStream fis = new FileInputStream(file)) {
  BufferedReader br=new BufferedReader(new InputStreamReader(fis));
  //char stringComma = new Character(',');
  while ((content = br.readLine()) != null) {
  // convert to char and display it
  Log.d(TAG, "called");
  arr.add(content);
  Log.d(TAG, "called");
  System.out.println(arr);
  }
  br.close();  
  } 
  catch (IOException e) {
  e.printStackTrace();
  }
  return arr.toString();
  }

可能是什么問題?

完成編寫后,應關閉Output stream ,如fou.close()

使用文件類時經常通過更改File.separator來代替/解決問題。 注意,完成工作后,需要在文件和數據庫中將其關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM