Java:使用文件阅读器在while循环中添加到字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10907582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: adding to a string array in a while loop using a file reader
提问by tyty5949
I have been making a little program that needs to read a list of golf courses that could be changeing and needs to be called when ever. Here is the code:
我一直在制作一个小程序,需要读取可能会发生变化并且需要随时调用的高尔夫球场列表。这是代码:
public class Courses {
public String[] courselist;
public void loadCourses() throws IOException{
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
while(count<1){
String s = reader.readLine();
if(s.equalsIgnoreCase("*stop*")){
reader.close();
count = 5;
}else{
courselist[counter] = s;
counter++;
}
s = "";
}
}
}
}
And now this is what is in the txt file.
现在这就是 txt 文件中的内容。
RiverChase
Steward Peninsula
Lake Park
Coyote Ridge
*stop*
Now when ever i start to run the program because i call the method instantly it gives me a throw exeption and it is because of the array. And i need to stay and array because i use it in a JComboBox. If you can help or fix the problem. Most likely im just doing it wrong, im a noob. Just help. Thanks in advance. I know all the file reader and stuff works because it prints out to the system correct, i just need help writing it to the array repetedly.
现在,当我开始运行程序时,因为我立即调用了该方法,它会给我一个抛出异常,这是因为数组。我需要留下来排列,因为我在 JComboBox 中使用它。如果你能帮助或解决问题。很可能我只是做错了,我是个菜鸟。只是帮助。提前致谢。我知道所有文件读取器和东西都可以正常工作,因为它可以正确地打印到系统中,我只需要帮助将其反复写入数组。
回答by Luiggi Mendoza
You should initialize your array before using it
你应该在使用它之前初始化你的数组
public static final MAX_SIZE = 100;
public String[] courselist = new String[MAX_SIZE];
回答by Arnaud
You'd better create a List that is easier to manipulate and convert it as an array at the end of the process :
您最好创建一个更易于操作的 List,并在过程结束时将其转换为数组:
List<String> list = new ArrayList<String>();
String [] array = list.toArray(new String [] {});
Here is a possible implementation of the loading using a List :
这是使用 List 加载的可能实现:
public static String [] loadCourses() throws IOException {
File f = new File("src//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>();
while (true){
String s = reader.readLine();
if (s == null || s.trim().equalsIgnoreCase("*stop*")){
break;
} else{
courses.add(s);
}
}
return courses.toArray(new String [] {});
}
Also why use a stopkeyword ? You could simply stop the process when you reach the end of the file (when s is null).
另外为什么要使用stop关键字?当您到达文件末尾时(当 s 为空时),您可以简单地停止该过程。
回答by Bohemian
Change your code to assign a new array during loadCourses()
, and add a call to loadCourses()
to your constructor:
更改您的代码以在 期间分配一个新数组loadCourses()
,并添加loadCourses()
对构造函数的调用:
public class Courses {
public String[] courselist;
public Courses() throws IOException { // <-- Added constructor
loadCourses(); // <-- Added call to loadCourses
}
public void loadCourses() throws IOException {
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>(); // <-- A List can grow
while(true){
String s = reader.readLine();
if (s.equalsIgnoreCase("*stop*")){
break;
}
courses.add(s);
}
courseList = courses.toArray(new String[0]); // <-- assign it here
}
}
This ensures that when you create an instance, it starts out life with the array initialised. Not only will you not get an error, but the data will always be correct (unlike other answers that simply create an empty (ie useless) array.
这确保当您创建一个实例时,它开始时初始化数组。您不仅不会收到错误,而且数据将始终是正确的(与其他简单地创建空(即无用)数组的答案不同。
Note that this code will work with any number of course names in the file (not just 5).
请注意,此代码适用于文件中任意数量的课程名称(不仅仅是 5 个)。
回答by Crazenezz
Here some example, without using the *stop*
:
这里有一些例子,不使用*stop*
:
public class ReadFile {
public static void main(String[] args) {
BufferedReader reader = null;
List<String> coursesList = new ArrayList<>();
String[] courses;
try {
File file = new File("courses.txt");
reader = new BufferedReader(new FileReader(file));
String readLine;
do {
readLine = reader.readLine();
if(readLine == null)
break;
coursesList.add(readLine);
} while (true);
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
courses = coursesList.toArray(new String[coursesList.size()]);
for(int i = 0; i < courses.length; i++) {
System.out.println(courses[i]);
}
}
}