如何使用 Android 应用程序重命名 SD 卡上的文件?

发布于 2024-09-02 12:05:33 字数 340 浏览 6 评论 0原文

在我的 Android 应用程序中,我想在运行时重命名文件名。我该怎么做呢?

这是我的代码:

String[] command = {" mv", "sun moon.jpg"," sun_moon,jpg"};
try
{
    Process process = Runtime.getRuntime().exec(command);
} 
catch (IOException e)
{
    Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
}

我还使用了 renameTo(File f) 方法,但它不起作用。

In my Android application, I want to rename the file name at runtime. How can I do it?

This is my code:

String[] command = {" mv", "sun moon.jpg"," sun_moon,jpg"};
try
{
    Process process = Runtime.getRuntime().exec(command);
} 
catch (IOException e)
{
    Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
}

I also used renameTo(File f) method but it does not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

明月夜 2024-09-09 12:05:33

我建议使用 File.renameTo() 而不是运行 mv 命令,因为我相当确定后者不受支持。

您是否给出了 写入 SD 卡的应用程序权限

您可以通过 将以下内容添加到您的 AndroidManifest 中来完成此操作.xml

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

如果添加权限后不起作用,请在尝试重命名文件时检查设备日志是否有错误(使用 adb 命令或在Eclipse 中的 logcat 视图)。

访问 SD 卡时,不应硬编码路径,而应使用 Environment.getExternalStorageDirectory() 方法来获取目录。

以下代码对我有用:

File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);

如果您想检查该过程,您可以这样做:

boolean renamed = from.renameTo(to);

if (renamed) {
  Log.d("LOG","File renamed...");
}else {
  Log.d("LOG","File not renamed...");
}

I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..

Have you given your application permission to write to the SD Card?

You do this by adding the following to your AndroidManifest.xml:

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

If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).

When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.

The following code works for me:

File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);

and if you want to check the process, you can do like:

boolean renamed = from.renameTo(to);

if (renamed) {
  Log.d("LOG","File renamed...");
}else {
  Log.d("LOG","File not renamed...");
}
极致的悲 2024-09-09 12:05:33

您还可以显式给出完整路径而不指定目录...

File file = new File("Path of file which you want to rename");
File file2 = new File("new name for the file");
    boolean success = file.renameTo(file2);

you can also explicitly give the full path without specifying directory...

File file = new File("Path of file which you want to rename");
File file2 = new File("new name for the file");
    boolean success = file.renameTo(file2);
年华零落成诗 2024-09-09 12:05:33

我尝试添加权限。尽管它不起作用,但添加 File1.setWritable(true); 使我能够重命名该文件。

下面是我的代码片段:

if(from.setWritable(true))
    Log.d("InsertFragmentTwo ", "FileName==> Is Writable");
File two = new File(sdcard,""+imageCount+"."+s.substring((s.lastIndexOf(".")+1)));
if (from.renameTo(two)) {
    Log.d("InsertFragmentTwo ", "New FileName==> " + temp);
    imageCount++;
    retrofitImageUpload(temp);
} else
    Log.d("InsertFragmentTwo ", "File Renaming Failed");

I tried adding permissions. Even though it did not work, adding File1.setWritable(true); enabled me to rename the file.

Below is my code snippet:

if(from.setWritable(true))
    Log.d("InsertFragmentTwo ", "FileName==> Is Writable");
File two = new File(sdcard,""+imageCount+"."+s.substring((s.lastIndexOf(".")+1)));
if (from.renameTo(two)) {
    Log.d("InsertFragmentTwo ", "New FileName==> " + temp);
    imageCount++;
    retrofitImageUpload(temp);
} else
    Log.d("InsertFragmentTwo ", "File Renaming Failed");
意中人 2024-09-09 12:05:33
public void selectFile() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {
            "Select file from internal storage"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                    }
                }
            });
    pictureDialog.show();
}
public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(galleryIntent, GALLERY);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            File dir = Environment.getExternalStorageDirectory();
            if(dir.exists()){
                File from = new File(dir, String.valueOf(GALLERY));
                File to = new File(dir,"filerename.txt");
                if(from.exists())
                    from.renameTo(to);
            }
        }
    }
}
public void selectFile() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {
            "Select file from internal storage"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                    }
                }
            });
    pictureDialog.show();
}
public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(galleryIntent, GALLERY);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            File dir = Environment.getExternalStorageDirectory();
            if(dir.exists()){
                File from = new File(dir, String.valueOf(GALLERY));
                File to = new File(dir,"filerename.txt");
                if(from.exists())
                    from.renameTo(to);
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文