我有大约300-400张图片,大小为jpg格式的320x480像素。我必须在SD卡上添加这些图像。目前我将这些图像放在我项目的Drawable文件夹中。现在我想在sd卡上移动这些图像,并希望将此图像用于动画目的。我还想在我的应用程序首次启动时检查SD卡是否已安装。我不知道在Android中编程SD CARD所以请任何人有任何想法或初学者的链接,请让我知道。
CODE
ImageView imgAssets;
String path="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
path = Environment.getExternalStorageDirectory().toString();
try {
copyFromAsstesToSDCard();
readFromSDCard();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void readFromSDCard() {
// TODO Auto-generated method stub
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir.getAbsolutePath()+ "/cat_angry10.jpg");
// i have kept text.txt in the sd-card
//System.out.println(file.toString());
if(file.exists()) // check if file exist
{
try {
Bitmap bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageState() + "/cat_angry10.jpg");
//imgAssets.setImageBitmap(bitMap);
imgAssets.setBackgroundDrawable(new BitmapDrawable(bitMap));
}
catch (Exception e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
else
{
System.out.println("Sorry file doesn't exist!!");
}
}
public void copyFromAsstesToSDCard() {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Images");
} catch (IOException e) {
Log.e("tag", e.getMessage());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Images/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + filename);
System.out.println(out.toString());
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
byte[] buffer = new byte[1024];
int read;
try {
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
从SD CARD读取图像时,我收到NullPointerException。
由于 Keyur
答案 0 :(得分:3)
以下是一些链接 - 如果您在使用这些链接时遇到问题,请发布您的代码,我会尝试进一步提供帮助。
Android write to sd card folder
http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html
https://sites.google.com/site/androidhowto/how-to-1/save-file-to-sd-card