2010-01-25 34 views
171

Tôi đang cố gắng để lưu tập tin của tôi vào vị trí sau
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); nhưng tôi nhận được ngoại trừ java.io.FileNotFoundException
Tuy nhiên, khi tôi đặt con đường như "/sdcard/" nó hoạt động.Làm thế nào để tạo thư mục tự động trên thẻ SD

Bây giờ tôi giả định rằng tôi không thể tự động tạo thư mục theo cách này.

Ai đó có thể đề xuất cách tạo mã directory and sub-directory bằng mã?

Trả lời

422

Nếu bạn tạo đối tượng File kết thúc tốt nhất thư mục cấp cao nhất bạn có thể gọi đó là phương pháp mkdirs() để tạo tất cả các thư mục cần thiết. Một cái gì đó như:

// create a File object for the parent directory 
File wallpaperDirectory = new File("/sdcard/Wallpaper/"); 
// have the object build the directory structure, if needed. 
wallpaperDirectory.mkdirs(); 
// create a File object for the output file 
File outputFile = new File(wallpaperDirectory, filename); 
// now attach the OutputStream to the file object, instead of a String representation 
FileOutputStream fos = new FileOutputStream(outputFile); 

Lưu ý: Nó có thể là khôn ngoan để sử dụng Environment.getExternalStorageDirectory() để nhận được "SD Card" thư mục như thế này có thể thay đổi nếu một điện thoại đến cùng trong đó có một cái gì đó khác hơn là một thẻ nhớ SD (như xây dựng -in flash, a'la iPhone). Dù bằng cách nào bạn cũng nên nhớ rằng bạn cần phải kiểm tra để đảm bảo nó thực sự ở đó vì thẻ SD có thể bị xóa.

CẬP NHẬT: Vì API cấp 4 (1.6) bạn cũng sẽ phải yêu cầu sự cho phép. Một cái gì đó như thế này (trong manifest) nên làm việc:

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

Cảm ơn fixXedd. Nó hoạt động hoàn hảo. –

+2

Không sao cả. Vui vẻ giúp đỡ. –

+1

có, các máy tính bảng Samsung phát hành sau đó sử dụng đèn flash tích hợp – CQM

57

Đã cùng một vấn đề và chỉ muốn nói thêm rằng AndroidManifest.xml cũng cần sự cho phép này:

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

Với API 8 và hơn nữa, vị trí của thẻ SD đã thay đổi. @ fiXedd của câu trả lời là tốt, nhưng đối với mã an toàn hơn, bạn nên sử dụng Environment.getExternalStorageState() để kiểm tra xem các phương tiện truyền thông có sẵn. Sau đó, bạn có thể sử dụng getExternalFilesDir() để điều hướng đến thư mục bạn muốn (giả sử bạn đang sử dụng API 8 trở lên).

Bạn có thể đọc thêm trong số SDK documentation.

38

Đây là những gì phù hợp với tôi.

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

trong biểu hiện của bạn và mã dưới đây

public static boolean createDirIfNotExists(String path) { 
    boolean ret = true; 

    File file = new File(Environment.getExternalStorageDirectory(), path); 
    if (!file.exists()) { 
     if (!file.mkdirs()) { 
      Log.e("TravellerLog :: ", "Problem creating Image folder"); 
      ret = false; 
     } 
    } 
    return ret; 
} 
+1

Tôi nên chuyển địa chỉ ở đây bằng cách nào? dưới dạng "folderPath" hoặc "/ folderPath" ???? Đường dẫn –

+0

là tên của thư mục bạn muốn tạo. Nếu bạn đã gửi đường dẫn như MusicDownload .. Nó sẽ tự động trở thành/sdcard/MusicDownload. Shajeel Afzal – shehzy

+0

Nó ném ngoại lệ java.io.IOException: mở không thành công: ENOENT (Không có tệp hoặc thư mục nào) –

5

tôi đã phải đối mặt với cùng một vấn đề, không thể tạo thư mục trên Galaxy S nhưng đã có thể tạo ra nó thành công trên Nexus và Samsung Droid.Làm thế nào tôi cố định nó là bằng cách thêm dòng mã sau đây:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/"); 
dir.mkdirs(); 
8

Hãy chắc chắn rằng lưu trữ bên ngoài đang hiện diện: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

private boolean isExternalStoragePresent() { 

     boolean mExternalStorageAvailable = false; 
     boolean mExternalStorageWriteable = false; 
     String state = Environment.getExternalStorageState(); 

     if (Environment.MEDIA_MOUNTED.equals(state)) { 
      // We can read and write the media 
      mExternalStorageAvailable = mExternalStorageWriteable = true; 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
      // We can only read the media 
      mExternalStorageAvailable = true; 
      mExternalStorageWriteable = false; 
     } else { 
      // Something else is wrong. It may be one of many other states, but 
      // all we need 
      // to know is we can neither read nor write 
      mExternalStorageAvailable = mExternalStorageWriteable = false; 
     } 
     if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) { 
      Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG) 
        .show(); 

     } 
     return (mExternalStorageAvailable) && (mExternalStorageWriteable); 
    } 
21

Trên thực tế tôi đã sử dụng một phần của @fiXedd asnwer và nó làm việc cho tôi:

//Create Folder 
    File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images"); 
    folder.mkdirs(); 

    //Save the path as a string value 
    String extStorageDirectory = folder.toString(); 

    //Create New file and name it Image2.PNG 
    File file = new File(extStorageDirectory, "Image2.PNG"); 

Hãy chắc chắn rằng bạn đang sử dụng mkdirs() không mkdir() để tạo ra đường dẫn đầy đủ

+0

Phần "này" của câu trả lời @fixedd như thế nào? Câu trả lời của ông là sử dụng 'File.mkdirs()'. Sau đó, ông đã cho thấy một ví dụ về việc sử dụng nó. – Doomsknight

+0

Thực sự tôi không thể nhớ sự khác biệt nhưng tôi nghĩ có một số chỉnh sửa ... Bằng cách tôi đã đề cập rằng tôi đã sử dụng câu trả lời của mình để nhận được giải pháp – Amt87

5

Đừng quên đảm bảo rằng bạn không có ký tự đặc biệt nào trong tên tệp/thư mục của mình. Xảy ra với tôi với ":" khi tôi đã đặt tên thư mục sử dụng biến (s)

không được phép ký tự trong tên tập tin/thư mục

"* /: <> \ |

U có thể tìm thấy mã này hữu ích trong trường hợp này

mã dưới đây loại bỏ tất cả ":" và thay thế chúng bằng "-"

//actualFileName = "qwerty:asdfg:zxcvb" say... 

    String[] tempFileNames; 
    String tempFileName =""; 
    String delimiter = ":"; 
    tempFileNames = actualFileName.split(delimiter); 
    tempFileName = tempFileNames[0]; 
    for (int j = 1; j < tempFileNames.length; j++){ 
     tempFileName = tempFileName+" - "+tempFileNames[j]; 
    } 
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/"); 
    if (!file.exists()) { 
     if (!file.mkdirs()) { 
     Log.e("TravellerLog :: ", "Problem creating Image folder"); 
     } 
    } 
.
+0

+1 ya tôi cũng đã thử: vấn đề đó và bị xóa: và tất cả các ký tự đặc biệt khác. –

1

Bạn có thể sử dụng/sdcard/thay vì Environment.getExternalStorageDirectory()

private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/"; 

File dbdir = new File(DB_PATH); 
dbdir.mkdirs(); 
+3

Không, bạn không nên sử dụng đường dẫn mã hóa cứng thay vì gọi API thích hợp. Làm như vậy giới thiệu một sự phụ thuộc không phụ thuộc vào chi tiết của một triển khai cụ thể. –

5
File sdcard = Environment.getExternalStorageDirectory(); 
File f=new File(sdcard+"/dor"); 
f.mkdir(); 

này sẽ tạo ra một thư mục có tên dor trong sdcard của bạn. rồi tìm nạp tệp cho eg- filename.json được chèn thủ công vào thư mục dor. Giống như:

File file1 = new File(sdcard,"/dor/fitness.json"); 
....... 
..... 

< sử dụng-phép android: name = "android.permission.WRITE_EXTERNAL_STORAGE" />

và đừng quên để thêm mã trong manifest

3
 //Create File object for Parent Directory 
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper"); 
if (!wallpaperDir.exists()) { 
wallpaperDir.mkdir(); 
} 


File out = new File(wallpaperDir, wallpaperfile); 
FileOutputStream outputStream = new FileOutputStream(out); 
3

Chỉ cần hoàn thành Bài của Vijay ...


Manifest

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

Chức năng

public static boolean createDirIfNotExists(String path) { 
    boolean ret = true; 

    File file = new File(Environment.getExternalStorageDirectory(), path); 
    if (!file.exists()) { 
     if (!file.mkdirs()) { 
      Log.e("TravellerLog :: ", "Problem creating Image folder"); 
      ret = false; 
     } 
    } 
    return ret; 
} 

Cách sử dụng

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir 
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt 

Bạn có thể kiểm tra lỗi

if(createDirIfNotExists("mydir/")){ 
    //Directory Created Success 
} 
else{ 
    //Error 
} 
6

tôi phải đối mặt với cùng một vấn đề. Có hai loại quyền trong Android:

  • nguy hiểm (truy cập vào danh bạ, ghi vào bộ nhớ bên ngoài ...)
  • Bình thường (quyền bình thường sẽ tự động được sự chấp thuận của Android trong khi quyền nguy hiểm cần phải được sự chấp thuận của người dùng Android.)

Dưới đây là chiến lược để có được quyền nguy hiểm trong Android 6,0 ​​

  • Kiểm tra xem bạn có được phép cấp
  • Nếu ứng dụng của bạn đã được cấp quyền, hãy tiếp tục và thực hiện bình thường.
  • Nếu ứng dụng của bạn không có sự cho phép nào, yêu cầu người sử dụng để phê duyệt
  • Nghe chính dùng trong onRequestPermissionsResult

Đây là trường hợp của tôi: Tôi cần phải ghi vào bộ nhớ bên ngoài.

Trước tiên, tôi kiểm tra xem tôi có sự cho phép:

... 
private static final int REQUEST_WRITE_STORAGE = 112; 
... 
boolean hasPermission = (ContextCompat.checkSelfPermission(activity, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); 
if (!hasPermission) { 
    ActivityCompat.requestPermissions(parentActivity, 
       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       REQUEST_WRITE_STORAGE); 
} 

Sau đó kiểm tra sự chấp thuận của người sử dụng:

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) 
    { 
     case REQUEST_WRITE_STORAGE: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
      { 
       //reload my activity with permission granted or use the features what required the permission 
      } else 
      { 
       Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }  
} 
1
ivmage.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent i = new Intent(
        Intent.ACTION_PICK, 
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

      startActivityForResult(i, RESULT_LOAD_IMAGE_ADD); 

     } 
    });` 
3

này sẽ làm cho thư mục trong sdcard với tên thư mục mà bạn cung cấp .

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name"); 
     if (!file.exists()) { 
      file.mkdirs(); 
     } 
Các vấn đề liên quan