我有多个要写入的文件,因此我尝试使用FileWriter
和PrintWriter
的数组。我甚至用try和catch包围了这些语句,但是应用程序仍崩溃并给出了错误:
java.lang.NullPointerException:尝试写入空数组
这就是我所做的:
在主Activity
类中,我声明了一个FileWriter
和
private FileWriter outStream[];
private PrintWriter printWriter[];
在onCreate
函数中我做了这个:
try {
outStream[0] = new FileWriter(finalFile_Acc, true);
printWriter[0]= new PrintWriter(outStream[0]);
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream[1] = new FileWriter(finalFile_Gyro, true);
printWriter[1]= new PrintWriter(outStream[1]);
} catch (IOException e) {
e.printStackTrace();
}
PS:我无法在同一位置声明并初始化FileWriter
和PrintWriter
。
答案 0 :(得分:1)
对于PrintWriter,您应该像这样使用它
PrintWriter printWriter[];
int numberOfPrintWriters = 10;
StringWriter stringWriter = new StringWriter();
printWriter = new PrintWriter[numberOfPrintWriters];
//using first printWriter
PrintWriter printWriter[0] = new PrintWriter(stringWriter);
try {
printWriter[0].write(str, 0, 26);
//or
printWriter[0].print("ZZZ");
}catch(Exception e){
e.printStackTrace();
}finally {
printWriter[0].close();
}
//Similarly you can use other printWriters in array using their index like printWriter[i]
对于FileWriter,您可以像这样使用它
int numberOfFileWriters = 10;
FileWriter fWriter[];
fWriter = new FileWriter[numberOfFileWriters];
try{
//using first fileWriter
fWriter[0] = new FileWriter(file, true);
fWriter[0].write("content");
fWriter[0].flush();
}catch(Exception e){
e.printStackTrace();
}finally{
fWriter[0].close();
}
//Similarly you can use other fWriters in array using their index like fWriter[i]
如果要在externalSDCard中写入文件,那么
File file = new File(Environment.getExternalStorageDirectory() + " \filename.txt");