Java Android 似乎无法使用 FileOutputStream 更新文本文件

问题描述

我是 Android Java 开发的初学者,但我有几年的 Java 学校和大学经验。 我正在尝试使用 FileOutputStream 写入我的应用程序中资产文件夹中的文本文件,但它似乎根本没有写入,因为我使用 InputStream 之后读取文件并且没有任何更新。 我可以使用 inputstream 从同一个文件中读取数据,但无法使用 outputteam 写入文件。 这是我的代码

private void updateTextFile(String update) {
    FileOutputStream fos = null;

    try
    {
        fos = openFileOutput("Questions",MODE_PRIVATE);
        fos.write("Testing".getBytes());
    } 
    catch (FileNotFoundException e) 
    {
        e.printstacktrace();
    } 
    catch (IOException e) 
    {
        e.printstacktrace();
    } 
    finally 
    {
        if(fos!=null)
        {
            try 
            {
                fos.close();
            } 
            catch (IOException e) 
            {
                e.printstacktrace();
            }
        }
    }

    String text = "";

    try
    {
        InputStream is = getAssets().open("Questions");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        text = new String(buffer);
    } 
    catch (IOException e) 
    {
        e.printstacktrace();
    }
    System.out.println("Tesing output " + text);
}

文本文件中没有任何内容,它只是输出

I/System.out: Tesing output 

不胜感激

解决方法

您的问题是因为您写入不同的文件并读取不同的文件。 openFileOut() 将根据上下文创建一个私有文件。 getAssets.open() 将在您的应用程序的资产文件夹中为您提供一个文件。 我想你想要的是InputStream is = openFileInput("Questions");

编辑

这是 FileInputStreamFileOutputStream 的示例。

String file = "/storage/emulated/0/test.txt";
OutputStream os = null;
InputStream in = null;
        
try {
    //To write onto a file.
    os = new FileOutputStream(new File(file));
    os.write("This is a test".getBytes(StandardCharsets.UTF_8));
    os.flush();
    //To read a file
    in = new FileInputStream(new File(file));
    byte[] store = new byte[8192];
    for(int i; (i=in.read(store,8192)) != -1; ) {
        System.out.print(new String(store,i,StandardCharsets.UTF_8));
    }
    System.out.println();
} catch(IOException e) {
} finally {
    if(os != null) try { os.close(); } catch(Exception ee) {}
    if(in != null) try { in.close(); } catch(Exception ee) {}
}   

不要忘记在 Manifest.xml 中设置写权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mypackagename.io"
    android:versionCode="1"
    android:versionName="4.3" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18"/>
        <uses-permission android:name="android.permission.VIBRATE"/>
        <uses-permission 
         android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
...