0

我一直在尝试在我的 Android 应用程序中写入sdcard 存储(目标 API 11)

我已经成功地在以下名为“BPAExp_data”的代码中创建了目录,但它根本没有创建新文件。我很困惑为什么,因为它没有出现在 logcat 中!!。

这是我的 onCreate() 方法

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text_logger);
    String data = "asdfghjkl.."

    //The filename of the log file
    filename = getIntent().getExtras().getString("Filename");

    //Save Test data button
    Button saveData = (Button)findViewById(R.id.saveDataButton);
    saveData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
        // Save Data in file and go back to home screen
        addtoKeyLogFile(data);              

        //Make intent for the Main Activity screen
        Intent main_intent = new Intent(TextLogger.this, MainActivity.class);
        startActivity(main_intent);
        }
    });

这是我称为 addKeyLogFile() 的方法

    public void addtoKeyLogFile(String data){       
    FileOutputStream f = null;
    File data_file;
    try {
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/BPAExp_data");
        dir.mkdirs();
        data_file = new File(dir, filename);
        f = new FileOutputStream(data_file);
        // if file doesn't exists, then create it
        if (!data_file.exists()) {
            data_file.createNewFile();
            Toast.makeText(TextLogger.this, "File GOT CREATED!", Toast.LENGTH_SHORT).show();
        }

        // get the content in bytes
        byte[] dataInBytes = data.getBytes();

        f.write(dataInBytes);
        f.flush();
        f.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.d("TextLogger onCreate: ", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("TextLogger onCreate: ", e.getMessage());
    } finally {
        try {
            if (f != null) {
                f.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我发现问题出在或附近

    f = new FileOutputStream(data_file);

因为当我在它之后放置一个 toast 消息时,它永远不会执行但是如果我在它之前放置一个 toast,它就会被执行!之后的意图也非常好!但我不明白,为什么它不起作用?

感谢任何人都可以提供的任何帮助!

4

1 回答 1

1

文件有多个构造函数。一个以 File 和 String 作为参数:

File dir = new File (sdCard , "BPAExp_data");
dir.mkdirs();
data_file = new File(dir, filename);

文件名的价值是什么?

删除这些行:

   if (!data_file.exists()) {
          data_file.createNewFile();
          Toast.makeText(TextLogger.this, "File GOT CREATED!", Toast.LENGTH_SHORT).show();
   }

当您停止写入文件时,将创建文件。

 f.close();

你叫它两次。仅将其保留在 finally 块内

总而言之,你确定你有东西要写吗?

byte[] dataInBytes = data.getBytes();

的长度是dataInBytes > 0

于 2013-01-22T14:45:00.910 回答