【发布时间】:2017-03-11 23:27:15
【问题描述】:
我有一个程序使用用户指定的文件名读取文件。 必须读取所有文件内容并将其存储在数组中。除了这个错误,我似乎已经正确地完成了 IO。我明白错误是什么,但不知道如何纠正。
EDIT:该数组已在文件中定义。
Zoo.java:284:错误:不兼容的类型:字符串无法转换为 动物
animals[ j ] = bufferedReader.readLine();
这是我的 readFile 子模块代码:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
感谢您的帮助。
【问题讨论】:
-
动物[]数组定义在哪里?您必须创建 Animal 类的新对象来填充数组。
animal [j] = new Animal( your line); -
Animals [] 数组已在同一个文件中定义。
-
使用读取所有行作为字符串,或使用字符串生成器。接下来使用字符串或字符串生成器的长度创建数组。最后,使用带有 string/stringbuilder 的 for 循环。长度和chaAt (i)
-
如果按行,先创建一个arraylist,使用arraylist.add()。然后做 String[] array = arraylist.toArray();
-
我正在使用手机,所以无法发布答案。
标签: java arrays io incomplete-type