[英]How to make FileInputStream and FileOutputStream in a java class
I wrote two methods to write and read data from Internal Storage, now that I want to put them in a non activity class I get errors at openFileOutput
and openFileInput
that says the method openFileInput
/ openFileOutput
is undefined for the type IOstream(name of my class) 我编写了两种方法从内部存储中写入和读取数据,现在,我想将它们放入非活动类中,在openFileOutput
和openFileInput
上出现错误,指出方法IOstream类型的openFileInput
/ openFileOutput
未定义(我的类的名称) )
I don't know how to fix it. 我不知道该如何解决。
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;
}
I'm looking for a way to put these methods in their own class 我正在寻找一种将这些方法放在自己的类中的方法
When you post a question and say "I get errors", actually posting said errors would go a long way to show people your problem. 当您发布问题并说“我遇到错误”时,实际上发布的错误将大大地向人们展示您的问题。
Taking a guess from your question and code, you've moved those methods to a class that does not extend Context, where those two methods are declared, so they can't be found. 通过对问题和代码的猜测,您已经将这些方法移到了不扩展Context的类中,在该类中声明了这两个方法,因此无法找到它们。
You need a reference to a context to be able to access those methods. 您需要对上下文的引用才能访问这些方法。
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.