我想将以前从简单的“备份”文本文件(txt)中读取的数据分配给类的n个可区分实例,以便以后可以使用这些实例。有没有办法使用某种循环来实现这一目标?
我尝试创建一个类“ Category”的多个实例c_0,c_1,..,c_n,这些实例将txt文件中相应行中的“类别名称”存储起来。该文件中的一行以类别名称开头,后跟逗号和可忽略的信息。现在,我每次在脚本开头调用此函数时,都希望有n个(=行数)不同的Category实例。到目前为止,我尝试了以下操作:
public class Backup{
static int maxC = 0;
public static void main(String[] args) throws IOException{
readC();
}
public static class Category{
private String categoryName;
public Category(String nameC){
categoryName = nameC;
}
}
private static void readC(){
BufferedReader br = null;
String line = "";
String seperate = ",";
int i = 0;
try{
br = new BufferedReader(new FileReader("C:/Users/Public/Category.txt"));
while((line = br.readLine()) != null){
String[] oneLineArray = line.split(seperate);
Category c_i = new Category(oneLineArray[0]); //I have a strong feeling
//that this only creates c_i and not the c_0 c_1 that I would want here
//How can one achieve that?
i++;
}
}catch(FileNotFoundException e){
System.out.println("File does not exist. "+e.getMessage());
}catch(IOException e){
System.out.println("I/O Error. "+e.getMessage());
}finally{
if (br != null){
try{
br.close();
}catch(IOException e){
System.out.println("I/O Error. "+e.getMessage());
}
}
}
maxC = i-1; //this is the amount (n) of instances created
}
}
就像我说的那样,我希望有多个实例,但是我有点怀疑循环的每个循环都是c_i
而不是c_0
等。有人可以启发我吗?我哪里出错了?
答案 0 :(得分:2)
c_i
只是变量名,i
只是一个像c
或_
这样的字符。
您要创建array或collection。 java.util.ArrayList
集合是最简单的选择,它将存储所有新对象并动态调整大小。
List<Category> categories = new ArrayList<>();
while((line = br.readLine()) != null){
String[] oneLineArray = line.split(seperate);
Category c = new Category(oneLineArray[0]);
categories.add(c);
}