繁体   English   中英

如何在Java类中制作FileInputStream和FileOutputStream

[英]How to make FileInputStream and FileOutputStream in a java class

我编写了两种方法从内部存储中写入和读取数据,现在,我想将它们放入非活动类中,在openFileOutputopenFileInput上出现错误,指出方法IOstream类型的openFileInput / openFileOutput未定义(我的类的名称) )

我不知道该如何解决。

public void write(String fileName, String content) throws IOException{
    FileOutputStream outStream = openFileOutput(fileName, Context.MODE_PRIVATE);
    outStream.write(content.getBytes());
    outStream.close();
}

public String read(String fileName) throws IOException{
    FileInputStream inStream = openFileInput(fileName);

    String content = null;
    byte[] readByte = new byte[inStream.available()];

    while(inStream.read(readByte) != -1){
        content = new String(readByte);
    }
    inStream.close();
    return content;
}

我正在寻找一种将这些方法放在自己的类中的方法

当您发布问题并说“我遇到错误”时,实际上发布的错误将大大地向人们展示您的问题。

通过对问题和代码的猜测,您已经将这些方法移到了不扩展Context的类中,在该类中声明了这两个方法,因此无法找到它们。

您需要对上下文的引用才能访问这些方法。

public void write(Context context, String fileName, String content) throws IOException{
    FileOutputStream outStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
    outStream.write(content.getBytes());
    outStream.close();
}

public String read(Context context, String fileName) throws IOException{
    FileInputStream inStream = context.openFileInput(fileName);

    String content = null;
    byte[] readByte = new byte[inStream.available()];

    while(inStream.read(readByte) != -1){
        content = new String(readByte);
    }
    inStream.close();
    return content;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM