【问题标题】:weird behaviour of setting new File Name in android在android中设置新文件名的奇怪行为
【发布时间】:2014-06-24 10:32:39
【问题描述】:

我需要用 Java 在 Andorid 中创建新文件。我这样做:

 public static File getAbosoluteFile(String relativePath, Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return new File(context.getExternalFilesDir(null),  "AE "  +".jpg");
        } else {
            Toast.makeText(context, "internal", Toast.LENGTH_SHORT).show();
            return new File(context.getFilesDir(), "AE"  +".jpg");
        }
    }

但是当我这样说时-它可以正常工作,但是当我更改名称时,例如使用方法中的字符串:

 public static String getCurrentDate()
 {
     String returnDate = null;
     Calendar currentDate = Calendar.getInstance();
     int minute = currentDate.get(Calendar.MINUTE);
     String editedMinute;
     if (minute<10)
         editedMinute = "0"  + Integer.toString(minute);
     else 
         editedMinute = Integer.toString(minute);
     returnDate= (Integer.toString((currentDate.get(Calendar.MONTH) + 1)) + "/" +Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH)) + "/" +Integer.toString(currentDate.get(Calendar.YEAR))  + " " +
             Integer.toString(currentDate.get(Calendar.HOUR_OF_DAY)) + ":" + editedMinute);
     return returnDate;

 }

所以,即使我使用return new File(context.getExternalFilesDir(null), "12/12/12 " +".jpg"); 该文件也没有创建。我试图在名称中使用筛选 - 认为原因在此,但结果相同。 Java 的new File(File dir, String name) 是否如此依赖于名称格式?还是什么原因?

【问题讨论】:

  • 文件路径中不能有“:”。还有其他被禁止的字符。 LogCat 会告诉你的!您可以使用“/”,但随后您将引入子目录。
  • 为什么要减去?我添加了描述。
  • 当您在第一种方法中没有使用 String relativePath 时,您将被否决(顺便说一句,不是我)。此外,您没有显示如何使用getCurrentDate() 的返回值来调用getAbosoluteFile()。当您不使用该参数时,Wich 将不起作用。而且..与其显示getCurrentDate() 的代码,不如告诉您您尝试在路径名中使用“12/13:23344”。你应该已经发布了 LogCat。简而言之:一个非常糟糕的帖子......
  • greenapps,谢谢你的解释。以后会考虑的。

标签: java android file


【解决方案1】:

您不能在文件名中使用/。它用作文件分隔符。

例如,如果您的 SD 卡中有一个名为 App 的文件夹,并且其中有一个名为 Sub 的子文件夹,则路径类似于 mnt/sdcard/App/Submnt/sdcard 只是举例,它不固定)

所以你可以看到为什么你不能在文件名中使用/

尝试使用_ 代替/

【讨论】:

    猜你喜欢
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多