【问题标题】:What is a suitable name for text File文本文件的合适名称是什么
【发布时间】:2014-10-05 16:42:42
【问题描述】:

在我的应用程序中,我将游戏中的数据保存到 .txt file.

我现在遇到的问题是,如果游戏时间超过一分钟,文本文件的 String 名称会导致文件被分成两部分。

例如如果它在9.22am9.23am 上播放,则会创建两个单独的文件。

如何创建一个更合适的文件名,该文件名对每个文件都是唯一的。

与文本文件名称相关的代码:

Time t= new Time();
            t.setToNow();
            int timeFileMinute= t.minute;
            int timeFileDate= t.yearDay;
            int timeFileYear= t.year;

            //creating file name
            String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;

完全写入文件方法:

public void writeToFileEEGPower(String data){


            Time t= new Time();
            t.setToNow();
            int timeFileMinute= t.minute;
            int timeFileDate= t.yearDay;
            int timeFileYear= t.year;

            //creating file name
            String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;

            //creating the file where the contents will be written to
            File file= new File(dir, fileName + ".txt");

            FileOutputStream os;

            try{

                boolean append= true;

                os= new FileOutputStream(file, append);

                String writeMe =data + "\n";


                os.write(writeMe.getBytes());

                os.close();
            } catch(FileNotFoundException e){

                e.printStackTrace();
            }catch(IOException e){

                e.printStackTrace();
            }

        }

【问题讨论】:

  • 我不明白。如果您不想在 txt 的文件名中使用时间,为什么?
  • 您的问题是您不断重新导出文件名。您可能应该决定什么构成会话(在 Android 上相当重要,除非您的游戏定义了“结束”),通过您选择的任何方法创建文件名,然后在会话期间使用相同的名称.
  • 不要在 writeToFileEEGPower() 方法中分配文件名,而是创建一个类级变量并在构造函数中分配它。
  • @Adrian - 是的,作为一种基本机制,但 Android 可能会在明显的用户会话中保留 Activity 类的实例数小时或数天。因此,可能需要使用一些针对此特定应用程序所需的用户体验进行调整的逻辑来决定何时开始新会话并分配新文件名。

标签: android text time


【解决方案1】:

编辑:您应该首先考虑生成唯一文件名(如随机文件名)的其他策略。

你可以这样做:

String fileName = new Date().getTime() + '.txt';

String fileName = new SimpleDateFormat("YYYYMMDDhhmmss'.txt'").format(new Date().getTime());

一种随机生成文件名的方法是:

String name = String.format("%s.txt", RandomStringUtils.randomAlphanumeric(10));

看看这个相关的 SO 问题:

【讨论】:

  • 这不能回答所提出的问题。发帖者已经完成了创建一个以时间戳为名称的文件,加上秒只会让问题更糟
  • 您没有阅读问题中的问题陈述。随意的名字会更糟。
猜你喜欢
  • 2015-10-26
  • 2011-07-03
  • 2015-05-12
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多