Java 正在将文件读入数组。。。我不明白错误是从哪里来的
//将文件读入字符串数组Java 正在将文件读入数组。。。我不明白错误是从哪里来的,java,arrays,Java,Arrays,//将文件读入字符串数组 public String[] readFixedString()throws FileNotFoundException { int i = 0; Scanner fileIn=null; try { fileIn = new Scanner(new FileInputStream("Spices.txt")); } catch (IOException e) { System.out.println(e.getMessag
public String[] readFixedString()throws FileNotFoundException
{
int i = 0;
Scanner fileIn=null;
try
{
fileIn = new Scanner(new FileInputStream("Spices.txt"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
while(fileIn.hasNextLine())
{
this.textfile[i++] = fileIn.nextLine();
}
fileIn.close();
return textfile;
}
主要方法
public static void main(String[] args)throws FileNotFoundException
{
ProductData pd=new ProductData();
pd.readFixedString();
}
java.lang.NullPointerException
在ProductData.readFixedString(ProductData.java:57)
位于ProductData.main(ProductData.java:125)
在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处
位于sun.reflect.NativeMethodAccessorImpl.invoke(未知源)
在sun.reflect.DelegatingMethodAccessorImpl.invoke处(未知源)
位于java.lang.reflect.Method.invoke(未知源)
位于u.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
我不明白我的错误来自何处,我的文件确实存在,并且路径正被跟踪到我检查的正确位置,只需读取文件,而不将条目放入数组中。textfile很可能是
null
,请确保正确初始化它:
this.textfile = new String[your_size];
或者,按照建议,使用列表
实现,例如ArrayList
:
private final List<String> textFile = new ArrayList<String>();
private final List textFile=new ArrayList();
尝试以下方法:
{
File f=new File("test.txt");
LineNumberReader lineReader=new LineNumberReader(new FileReader(f));
int counter=0;
while(lineReader.ready())
{
lineReader.readLine();
}
lineReader.close();
counter=lineReader.getLineNumber();
System.out.println(counter);
String [] str=new String[counter];
Scanner scan=new Scanner(f);
int i=0;
while(scan.hasNextLine())
{
str[i++]=scan.nextLine();
}
scan.close();
for (String string : str)
{
System.out.println(string);
}
}
你可能想试试这个,因为你说你的文件有问题,也要确保你的 文件路径正确。这是一个使用ArrayList的实现
ArrayList<String> textFile = new ArrayList<String>();
File file = new File("Spices.txt");
Scanner fileIn = new Scanner(file);
while(fileIn.hasNextLine()){
textFile.add(fileIn.nextLine());
}
fileIn.close();
ArrayList textFile=new ArrayList();
File File=新文件(“Spices.txt”);
Scanner fileIn=新扫描仪(文件);
while(fileIn.hasNextLine()){
textFile.add(fileIn.nextLine());
}
fileIn.close();
您在哪里声明了textfile?当您修复此问题时,您将使用该数组超出范围。除非你把它弄大了。。。最好使用一些列表实现。例如ArrayList,我认为他应该使用ArrayList之类的东西,因为OP不知道要使用的字符串数组的大小initialize@SarthakMittal肯定只是在这里指出问题:)