android java 文件操作相关

http://stackoverflow.com/questions/2130932/how-to-create-directory-automatically-on-sd-card

文件夹不存在时先创建

   1: public static boolean createDirIfNotExists(String path) {
   2:     boolean ret = true;
   3: 
   4:     File file = new File(Environment.getExternalStorageDirectory(), path);
   5:     if (!file.exists()) {
   6:         if (!file.mkdirs()) {
   7:             Log.e("TravellerLog :: ", "Problem creating Image folder");
   8:             ret = false;
   9:         }
  10:     }
  11:     return ret;
  12: }

确保sdcard可以读写

   1: private boolean isExternalStoragePresent() {
   2:  
   3:         boolean mExternalStorageAvailable = false;
   4:         boolean mExternalStorageWriteable = false;
   5:         String state = Environment.getExternalStorageState();
   6: 
   7:         if (Environment.MEDIA_MOUNTED.equals(state)) {
   8:             // We can read and write the media
   9:             mExternalStorageAvailable = mExternalStorageWriteable = true;
  10:         } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
  11:             // We can only read the media
  12:             mExternalStorageAvailable = true;
  13:             mExternalStorageWriteable = false;
  14:         } else {
  15:             // Something else is wrong. It may be one of many other states, but
  16:             // all we need
  17:             // to know is we can neither read nor write
  18:             mExternalStorageAvailable = mExternalStorageWriteable = false;
  19:         }
  20:         if (!((mExternalStorageAvailable) &;& (mExternalStorageWriteable))) {
  21:             Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
  22:                     .show();
  23: 
  24:         }
  25:         return (mExternalStorageAvailable) &;& (mExternalStorageWriteable);
  26:     }

路径中不能有非法字符

 

   1:  
   2: not allowed characters in file/folder names
   3:  
   4: " * / : < > ? \ |
   5: U may find this code helpful in such a case.
   6: The below code removes all ":" and replaces them with "-"//actualFileName = "qwerty:asdfg:zxcvb" say...
   7:  
   8:     String[] tempFileNames;
   9:     String tempFileName ="";
  10:     String delimiter = ":";
  11:     tempFileNames = actualFileName.split(delimiter);
  12:     tempFileName = tempFileNames[0];
  13:     for (int j = 1; j < tempFileNames.length; j++){
  14:         tempFileName = tempFileName+" - "+tempFileNames[j];
  15:     }
  16:     File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
  17:     if (!file.exists()) {
  18:         if (!file.mkdirs()) {
  19:         Log.e("TravellerLog :: ", "Problem creating Image folder");
  20:         }
  21:     }

下载图片保存到sdcard

   1: package com.v3.thread.fetchImage;
   2: 
   3: import java.io.File;
   4: import java.io.FileOutputStream;
   5: import java.io.IOException;
   6: import java.io.InputStream;
   7: import java.net.HttpURLConnection;
   8: import java.net.MalformedURLException;
   9: import java.net.URL;
  10: import android.app.Activity;
  11: import android.graphics.Bitmap;
  12: import android.graphics.BitmapFactory;
  13: import android.os.Bundle;
  14: import android.os.Environment;
  15: import android.provider.MediaStore;
  16: import android.util.Log;
  17: import android.view.View;
  18: import android.widget.Button;
  19: import android.widget.EditText;
  20: import android.widget.ImageView;
  21: import android.widget.Toast;
  22:  
  23: public class MainThreadActivity extends Activity {
  24:     ImageView imView;
  25:     EditText ed1;
  26:     Bitmap bmImg;
  27:     Button bt, btSave;
  28:     String imageUrl = "";
  29:     int visibilty = 0;
  30:  
  31:     /** Called when the activity is first created. */
  32:     @Override
  33:     public void onCreate(Bundle icicle) {
  34:         super.onCreate(icicle);
  35:         setContentView(R.layout.main);
  36:         ed1 = (EditText) findViewById(R.id.edURL);
  37:         btSave = (Button) findViewById(R.id.btnSave);
  38:  
  39:         bt = (Button) findViewById(R.id.btnLoad);
  40:         bt.setOnClickListener(getImgListener);
  41:  
  42:         imView = (ImageView) findViewById(R.id.imview);
  43:         Log.i("img already downloaded", "img");
  44:         btSave.setOnClickListener(new View.OnClickListener() {
  45:             public void onClick(View arg0) {
  46:                 Log.i("img url", "Under Save");
  47:                 saveImage();
  48:             }
  49:         });
  50:     }
  51:  
  52:     View.OnClickListener getImgListener = new View.OnClickListener() {
  53:  
  54:         public void onClick(View view) {
  55:             // TODO Auto-generated method stub
  56:             imageUrl = ed1.getText().toString();
  57:             if (imageUrl.equals(""))
  58:  
  59:                 Toast.makeText(getApplicationContext(), "Enter an URL first",   1000).show();       
  60: downloadFile(imageUrl);
  61:             Log.i("im url", imageUrl);
  62:             btSave.setVisibility(visibilty);
  63:         }
  64:  
  65:     };
  66: 
  67:     void downloadFile(String fileUrl) {
  68:         URL myFileUrl = null;
  69:         try {
  70:             myFileUrl = new URL(fileUrl);
  71:         } catch (MalformedURLException e) {
  72:             // TODO Auto-generated catch block
  73:             e.printStackTrace();
  74:         }
  75:         try {
  76:             HttpURLConnection conn = (HttpURLConnection) myFileUrl
  77:                     .openConnection();
  78:             conn.setDoInput(true);
  79:             conn.connect();
  80:             InputStream is = conn.getInputStream();
  81:             Log.i("im connected", "Download");
  82:             bmImg = BitmapFactory.decodeStream(is);
  83:  
  84:             imView.setImageBitmap(bmImg);
  85:         } catch (IOException e) {
  86:             // TODO Auto-generated catch block
  87:             e.printStackTrace();
  88:         }
  89:     }
  90:  
  91:     void saveImage() {
  92:         File filename;
  93:         try {
  94:             String path = Environment.getExternalStorageDirectory().toString();
  95:             Log.i("in save()", "after mkdir");
  96:             new File(path + "/mvc/mvc").mkdirs();
  97:             filename = new File(path + "/mvc/mvc/var3.jpg");
  98:             Log.i("in save()", "after file");
  99:             FileOutputStream out = new FileOutputStream(filename);
 100:             Log.i("in save()", "after outputstream");
 101:             bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
 102:             out.flush();
 103:             out.close();
 104:             Log.i("in save()", "after outputstream closed");
 105:             MediaStore.Images.Media.insertImage(getContentResolver(),
 106:                     filename.getAbsolutePath(), filename.getName(),
 107:                     filename.getName());
 108:             bt.setText("Saved...");
 109:             Toast.makeText(getApplicationContext(),
 110:                     "File is Saved in  " + filename, 1000).show();
 111:         } catch (Exception e) {
 112:             e.printStackTrace();
 113:         }
 114:  
 115:     }
 116: }

你可能感兴趣的:(android java 文件操作相关)