先展出源代码:
//打开图库
class B3 implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
}
}
//点击图片之后进行响应
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == 2){
Uri uri=data.getData(); //获取图片的path
//ContentResolver cr = this.getContentResolver();
//bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
String[] proj = {MediaStore.Images.Media.DATA};
//好像是android多媒体数据库的封装接口,具体的看Android文档
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, proj, null, null, null);
//按我个人理解 这个是获得用户选择的图片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
//最后根据索引值获取图片路径
String path = cursor.getString(column_index);
System.out.println(path);
copyFile(path,newpath);
Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
}
}
}
//进行复制的函数
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (!oldfile.exists()) { //文件不存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
下面的是我的问题:
手机上显示文件复制成功,但是从文件管理器上发现并没有复制成功,这个复制的函数是我从网上找的,网上说newpath这个字符串是这个样子的newPath String 复制后路径 如:f:/fqf.txt 但是我的程序的newpath是newpath="/mnt/sdcard/美好时光",请大神指点迷津!!!