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

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

如何解决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"/>
...

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