我正在尝试将数组字符串存储在文本文件中并读取它。但我无法让它工作。我收到 NullPointerError。
Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at in.isuru.justconverter.FileDbTool.readFile(FileDbTool.java:41)
at in.isuru.justconverter.Test.main(Test.java:10)
这里有两节课。
package in.isuru.justconverter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class FileDbTool {
File dataFile;
ArrayList<String> filePath;
public void checkFile(){
dataFile = new File("db.txt");
if(dataFile.exists()){
readFile();
}else{
try {
dataFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Coudn't Create New File!");
System.exit(1);
}
}
}
public void readFile(){
int len;
try{
char[] chr = new char[4096];
StringBuffer buffer = new StringBuffer();
FileReader reader = new FileReader(dataFile);
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
}finally {
reader.close();
}
System.out.println(buffer.toString());
StringTokenizer st = new StringTokenizer(buffer.toString(), ",");
while (st.hasMoreTokens()) {
String value = st.nextToken();
filePath = null;
filePath = new ArrayList<String>();
filePath.add(value);
}
}catch(IOException e){
JOptionPane.showMessageDialog(null, "Read Error");
}
}
public String[] getFilePathArray(){
readFile();
return filePath.toArray(new String[filePath.size()]);
}
public File[] getFiles(){
String[] paths = getFilePathArray();
ArrayList<File> files = new ArrayList<File>();
for(int i = 0; i < paths.length; i++){
File file = new File(paths[i]);
files.add(file);
}
return files.toArray(new File[files.size()]);
}
public void eraseFile(){
dataFile.delete();
}
public void writeFile(String[] stuff){
try{
BufferedWriter out = new BufferedWriter(new FileWriter(dataFile, true));
out.append(stuff + ",");
}catch(IOException e){
}
}
public void writeToDb(String[] array){
writeFile(array);
}
}
和主班
package in.isuru.justconverter;
公共类测试{
/**
* @param args
*/
public static void main(String[] args) {
FileDbTool app = new FileDbTool();
app.checkFile();
}
}
嗯,这是一个摇摆程序的一部分。我正在尝试将文本文件用作小型数据库。