public class IOReader
{
static ArrayList<FlashCard> cards = new ArrayList<FlashCard>();
static File file = new File("temp.txt");
public static void fillArray() throws FileNotFoundException, IOException
{
FileInputStream fiStream = new FileInputStream(file);
if(file.exists())
{
try( BufferedReader br = new BufferedReader( new InputStreamReader(fiStream) )
{
String line;
String[] seperated;
while( (line = br.readLine()) != null)
{
try
{
seperated = line.split(":");
String foreign = seperated[0];
String english = seperated[1];
cards.add( new FlashCard(foreign, english) );
System.out.println(foreign + " : " + english);
}
catch(NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally{
br.close();
}
}
}
}
else{
System.err.print("File not found");
throw new FileNotFoundException();
}
}
public static void main(String[] args)
{
try{
fillArray();
}
catch (Exception e){}
for(FlashCard card: cards)
System.out.println( card.toString() );
System.out.print( cards.size() );
}
}
我的文本文件如下:
Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
... et alia
我的FlashCard课程非常简单;它只需要两个字符串作为参数。但问题是每次运行时输出都是除了main方法中打印的0之外没有打印任何内容,表明ArrayList为空。我提前感谢你的任何帮助,我们将不胜感激。
答案 0 :(得分:1)
有一点需要考虑:
fillArray()
中的main()
,因此fillArray()
中的代码会更多
可读,你不会隐藏例外。main()
函数将使用它。Igal类代码:
public class Igal {
private String st1;
private String st2;
public Igal(String s1, String s2){
st1 = s1;
st2 = s2;
}
/**
* @return the st1
*/
public String getSt1() {
return st1;
}
/**
* @param st1 the st1 to set
*/
public void setSt1(String st1) {
this.st1 = st1;
}
/**
* @return the st2
*/
public String getSt2() {
return st2;
}
/**
* @param st2 the st2 to set
*/
public void setSt2(String st2) {
this.st2 = st2;
}
@Override
public String toString(){
return getSt1() + " " + getSt2();
}
}
代码:
static List<Igal> cards = new ArrayList<>();
static File file = new File("C:\\Users\\xxx\\Documents\\NetBeansProjects\\Dictionary\\src\\temp.txt");
public static void fillArray() throws FileNotFoundException, IOException {
FileInputStream fiStream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fiStream));
String line;
String[] seperated;
while ((line = br.readLine()) != null) {
seperated = line.split(":");
String foreign = seperated[0];
String english = seperated[1];
System.out.println(foreign + " : " + english);
Igal fc = new Igal(foreign, english);
cards.add(fc);
}
}
public static void main(String[] args) {
try {
fillArray();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("------------------");
for (Igal card : cards) {
System.out.println(card.toString());
}
System.out.print("the size is " + cards.size()+"\n");
temp.txt内容如下
Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
输出:
------------------
Volare To Fly
Velle To Wish
Facere To Do / Make
Trahere To Spin / Drag
Odisse To Hate
the size is 5