我刚刚开始学习如何在java oi上写入文件和从文件读取。现在,我可以将简单的文本写入文件,也可以使用system.out.print读取它。现在的问题是,我试图用我学到的相同方法创建一个数组并将其存储在文件中,但是当我运行程序时,文件已创建但没有任何显示。请有什么事我可以做的,否则,下面是我的代码示例:
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File Veggies= new File ("C:\\Users\\user\\Desktop\\My Java Files\\Product.txt");
if(Veggies.exists())
System.exit(0);
PrintWriter output= new PrintWriter(Veggies);
output.println("These are the list of our products.");
String[] VeggiesArray={"Apples","Bananas","Oranges","Avocados","Strawberries"};
for(int i=0;i<=VeggiesArray.length;i++){
output.println("(" + i + ")" +" "+ VeggiesArray[i]);
}
output.close();
}
答案 0 :(得分:0)
File veggies= new File (".\\Product.txt");
PrintWriter output= new PrintWriter(veggies);
output.println("These are the list of our products.");
String[] veggiesArray={"Apples","Bananas","Oranges","Avocados","Strawberries"};
for(int i=0;(i<veggiesArray.length);i++) {
output.println("(" + i + ")" +" "+ veggiesArray[i]);
}
output.close();
摆脱了veggies.Exists(),因为它会只允许你生成一个文件时,没有先删除它。
修正了MadProgrammer指出的循环条件。