微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这种写入文件的方法是否正确?

如何解决这种写入文件的方法是否正确?

我在一家安卓工作室工作。我使用以下代码写入文件,但该文件不起作用。谁能告诉我为什么这段代码不起作用?

try {
    FileWriter fileWriter = new FileWriter("accounts.txt",true);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(tvUername.getText().toString()+","+tvEmail.getText().toString()+","+tvCPassword.getText().toString()+"\n");
    Toast.makeText(SignUpActivity.this,"account saved",Toast.LENGTH_SHORT).show();
    bufferedWriter.close();
    fileWriter.close();
} catch (IOException e) {
    e.printstacktrace();
}

解决方法

我认为你的代码很好。但如果它不起作用:

使用下面的代码,它可以工作文件

File rootStorage = new File(String.valueOf(getApplicationContext().getExternalFilesDir("storage/emulated/0"))); 


String actualFileName = new File(rootStorage.getAbsolutePath() + "/" + fileName)


  try {

        File textFile = new File(actualFileName);

        if (textFile.exists()) {
            System.out.println("File path exists = " + textFile.getAbsolutePath());

            // set to true if you want to append contents to text file
            // set to false if you want to remove preivous content of text
            // file
            FileWriter textFileWriter = new FileWriter(textFile,true);

            BufferedWriter out = new BufferedWriter(textFileWriter);

            // create the content string
            String contentString = new String(contents);

            // write the updated content
            out.write(contentString);
            out.close();
            System.out.println("Updaetd text file");

        }

如果您需要创建一个新文件然后编写然后使用以下代码:

   try {

        File file = new File(actualFileName);

        if (!file.exists()) {
            System.out.println("File path = " + file.getAbsolutePath());
            if (file.createNewFile()) {
                Toast.makeText(this,"File Name is sampleDeveloper.txt",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this,"File not Created",Toast.LENGTH_SHORT).show();
            }
        }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。