【问题标题】:Not able to read Files with same System.currentTimeMillis无法读取具有相同 System.currentTimeMillis 的文件
【发布时间】:2018-02-10 06:05:39
【问题描述】:

我有一个应用程序。每当用户在我的应用程序中录制歌曲时,我都会在 sdcard 中创建一个文件,其名称中带有时间戳。时间戳是使用 System.currentTimeMillis 创建的。我正在阅读其他活动中的这些文件。假设用户录制了一个文件,然后到 sdcard 并复制并粘贴第一个文件以生成 sdcard 中的其他文件。现在所有文件都有相同的 System.currentTimeMillis。现在,当我进行其他活动时,我看不到我的任何文件。如何防止复制粘贴具有相同时间戳的相同文件的这种行为。任何帮助将不胜感激。

【问题讨论】:

  • 请发布您的代码。
  • @Rumit 请看一下
  • 您无法阻止这种复制粘贴具有相同时间戳的相同文件的行为。至少当文件在 SD 卡上时。你可以换个思路。内部存储或其他。
  • @Rumit 即使在内部存储中,用户也可以复制文件
  • Now all the files have same System.currentTimeMillis. ???那个时间在文件名中。我无法想象如果你复制一堆文件,它们的文件名会改变。不清楚你在哪里抱怨。

标签: android file timestamp


【解决方案1】:

您无法阻止复制粘贴具有相同时间戳的相同文件的这种行为。至少当文件在 SD 卡上时。

您可以尝试的其他解决方案是使用HashMap,而不是ArrayList

你可以使用

HashMap<String, MyRecording> mHashMap = new HashMap<String, MyRecording>();

而不是

ArrayList<MyRecording> arrayList = new ArrayList<MyRecording>();

HashMap 中,您可以将文件名设置为键。所以不会重复。

关于hashmap的迭代,你可以看看How to efficiently iterate over each entry in a 'Map'?

编码愉快 :-)

【讨论】:

    【解决方案2】:

    android 系统是否允许两个文件以相同的名称存在于同一个地方?这很奇怪,我以前从未尝试过。

    无论如何,我会给你我的代码,我如何创建一个具有唯一文件名的文件,以及我如何将这些文件名加载到列表中以在列表视图中显示它们,希望可以帮助你解决问题。

    首先我创建一个唯一的文件名,顺便说一句 AUDIO_RECORDER_FOLDER 是一个字符串 =“我的记录文件夹”

        private String getFilename() {
        filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        File file = new File(filepath, AUDIO_RECORDER_FOLDER);
        if (!file.exists()) {
            file.mkdirs();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
        String currentDateTimeString = simpleDateFormat.format(new Date());
        //String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    
        return (file.getAbsolutePath() + "/" + currentDateTimeString + AUDIO_RECORDER_FILE_EXT);
    }
    

    然后当我开始录制时,我调用它来创建文件名:

    String filename = getFilename();
    ...
    fileOutputStream = new FileOutputStream(filename, true);
    ...(some codes)
    

    然后我从用户 sd 卡中加载它们(如果他有一张),或者从内部存储中加载它们(如果他没有这样的 sd 卡):

    filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/my records folder";
    File file = new File(filepath);
    files = file.list();
    if(files != null && files.length>0){
        records = new ArrayList<>();
        for(int i =0; i<files.length; i++){
           Records record = new Records();
           record.setTitle(files[i]);
           records.add(record);
        }
    }
    

    然后我将记录数组列表传递给我的适配器,就是这样。

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多