【问题标题】:Android not creating/appending a.txt fileAndroid 未创建/附加 a.txt 文件
【发布时间】:2015-04-27 16:01:39
【问题描述】:

这是从我的 android 活动中的 .txt 文件中读取的内容。虽然应用程序运行,但我发现没有创建/附加任何文件。在 logcat 中显示以下行,

java.io.FileNotFoundException: /home/Desktop/RiaC_android/Test/app/src/main/assets/SampleFile.txt: open failed: ENOENT (No such file or directory)

我目前使用的代码,虽然我之前尝试过, BufferedWriter out = new BufferedWriter( 新的 FileWriter("test_File.txt")); 但是,结果保持不变。

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView tv = (TextView)findViewById(R.id.textView);
File testFile = new File("/home/Desktop/RiaC_android/Test/app/src/main/assets", "SampleFile.txt");
FileWriter writer = null;
try {
writer = new FileWriter(testFile, true);
writer.write("Hello File!!");
writer.close();
} catch (IOException e) {
        e.printStackTrace();
}
if (testFile.exists())
tv.setText("File created!!");
}

public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.menu_main, menu);
       return true;
     }
}

关于我做错了什么有什么建议吗?

【问题讨论】:

  • 这个 /home/Desktop/RiaC_android/Test/app/src/main/assets 路径是什么意思?
  • 您是否在 manifest.xml 中授予了 WRITE_EXTERNAL_STORAGE 权限
  • 这只是我试图创建文件的地址。我仅将此用作测试目的。 @Anoop M
  • 是的,我已经授权了。 @Vishwajit Palankar
  • 您是否尝试在应用的资产文件夹中写入内容?

标签: android file


【解决方案1】:

您不能将文件写入资产文件夹。资产文件夹在运行时是只读的。选择一个不同的位置来保存您的数据。即,Environment.getExternalStorageDirectory() 不要使用 Environment.getExternalStorageDirectory().getAbsolutePath()。

要从资产中读取文件,请使用以下方法

public String readFromAsset(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
    fIn = context.getResources().getAssets()
            .open(fileName, Context.MODE_WORLD_READABLE);
    isr = new InputStreamReader(fIn);
    input = new BufferedReader(isr);
    String line = "";
    while ((line = input.readLine()) != null) {
        returnString.append(line);
    }
} catch (Exception e) {
    e.getMessage();
} finally {
    try {
        if (isr != null)
            isr.close();
        if (fIn != null)
            fIn.close();
        if (input != null)
            input.close();
    } catch (Exception e2) {
        e2.getMessage();
    }
}
return returnString.toString();
  }

【讨论】:

  • 效果很好。谢谢。另一方面,Android Studio 中是否没有选项不只使用 sdCard 来存储应用程序数据?我的意思是,就像在 Eclipse 中一样,我们可以使用 Assets 文件夹来存储应用程序数据以用于读写目的。
  • 根据/app/src/main的android studio资产文件夹的更新项目结构。如果找不到它。在里面创建一个名为'assets'的文件夹。我们可以把我们的项目构建时资产中的字体、css 等在运行时并不意味着。
【解决方案2】:

无法写入/asset 目录,因为它是只读的。

assets 文件夹就像文件夹 res、src、gen 等。这些都有助于提供不同的文件作为构建系统的输入,从而为您的应用生成 APK 文件。

在您的应用运行时,所有这些都是只读的。在运行时,您可以写入 SD 卡。

您不能在运行时使用File 访问assets/。您可以在运行时使用AssetManager 访问assets/,您可以通过getResources().getAssets() 获得。

要从/asset 文件夹中读取,请使用以下代码:

AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;

    try {
        inputStream = assetManager.open("SampleFile.txt");
           if ( inputStream != null)
                Log.d("TAG", "It worked!");
        } catch (Exception e) {
            e.printStackTrace();
        }

【讨论】:

  • AssetManagerassetManager = getResources().getAssets();我收到一个错误,因为无法解析方法 getResources()..
  • 如果你想在你的活动之外使用它,那么你应该传递你的活动上下文并使用该上下文来调用方法。
【解决方案3】:

您不能修改资产文件夹中的文件。只是认为它们是只读文件。

如果要创建文本文件并修改它们,请使用getExternalCacheDirnew File 方法创建文件。

public static File CreateTextFile(Context context, String filename) throws IOException {
    final File root = context.getExternalCacheDir();
    return new File(root, filename);
}

在下面追加编辑

1.要简单地编写文本,请执行以下操作

String text = "bla bla";
FileWriter writer=null;
    try {
            File file = CreateTextFile("something.txt"); // proposed method
            if(!file.exists())
                file.createNewFile();

            writer = new FileWriter(file);

            /** Saving the contents to the file*/
            writer.write(text);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2。要读取缓存文件,
检查此链接:https://stackoverflow.com/a/5971667/361100

3.再举一个例子
下面的示例是编写从互联网获取的文本。

String webUrl = "http://www.yourdata.com/data.txt";

    try {
        URL url = new URL(webUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);

        urlConnection.connect();
        File file = CreateTextFile("something.txt"); // proposed method

        if(!file.exists())
            file.createNewFile();

        FileOutputStream fileOutput = new FileOutputStream(file);

        InputStream inputStream = urlConnection.getInputStream();

        int totalSize = urlConnection.getContentLength();
        int downloadedSize = 0;

        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {

            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
        }

        fileOutput.close();
        if(downloadedSize==totalSize)
            filepath=file.getPath();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        filepath=null;
    }

【讨论】:

  • 使用此代码,我看到 .txt 文件保存在“app/build/intermediates/assets/debug”中。现在我如何从中读取?我可以在应用程序运行期间使用相同的“root”多次读取或附加文件吗?
  • @ree1991 // 你可以随时读/写,因为它被授予缓存目录用于此目的。我编辑了如何读/写文件的答案。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 2015-04-27
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多