Java-从文件中读取类别列表
我有多个.txt文件,其中包含不同类别中不同数量的水果。例如:Java-从文件中读取类别列表,java,arrays,string,file,Java,Arrays,String,File,我有多个.txt文件,其中包含不同类别中不同数量的水果。例如: General Fruits: apple orange grape Specific Fruits x: 0: dragon fruit 1: lychee 2: star fruit 3: pomegranate Specific Fruits y: 0: coconut 1: durian 假设我可以读取文件并将苹果、橘子、葡萄存储到一个普通水果[]字符串数组中,将龙果、荔枝、杨桃、石榴存储到一个特定的水果[]字符串数组中
General Fruits:
apple
orange
grape
Specific Fruits x:
0: dragon fruit
1: lychee
2: star fruit
3: pomegranate
Specific Fruits y:
0: coconut
1: durian
假设我可以读取文件并将苹果、橘子、葡萄存储到一个普通水果[]字符串数组中,将龙果、荔枝、杨桃、石榴存储到一个特定的水果[]字符串数组中,将椰子、榴莲存储到一个特定的水果[]字符串数组中
到目前为止,我已经:
try (BufferedReader br = new BufferedReader(new FileReader(fileChooser.getSelectedFile().toString()))) {
String line;
String [] generalFruit = new String[50];
String [] specificFruitX = new String[50];
String [] specificFruitY = new String[50];
while ((line = br.readLine()) != null) {
// process the line.
System.out.println(line);
}
}
谢谢。是的,显然你能做到 你需要遵循以下步骤,你会做到的 -1在while循环中检查是否有
if(line.equals(“General Fruits:”)
-2如果上述条件为真,则生成一个布尔值,该布尔值现在打开。
-3现在查看该布尔值是否为on,并将下一个字符串放入数组
generalFruit[]
这真的很容易,你可以做到 看看这段代码,我已经让它的工作只是阅读一般的水果。 通过理解rest,您可以在rest上工作
String [] generalFruit = new String[4];
boolean generalFruitboolean=false;
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
int i=0;
while ((line = br.readLine()) != null) {
if(line.equals("General Fruits:") == true){
generalFruitboolean=true;
i=0;
}
if(generalFruitboolean==true && i<4){
generalFruit[i]=line;
i++;
}
}
for (int j = 0; j < generalFruit.length; j++) {
System.out.println(generalFruit[j]);
}
}
String[]generalFruit=新字符串[4];
布尔GeneralRuitBoolean=false;
try(BufferedReader br=newbufferedreader(newfilereader(“test.txt”)){
弦线;
int i=0;
而((line=br.readLine())!=null){
if(line.equals(“一般结果:”)==true){
GeneralRuitBoolean=true;
i=0;
}
如果(generalRuitBoolean==true&&i是,有很多简单的方法可以读取文件并将值设置到列表中,我通常使用*.properties文件来显示静态组合,如果您想读取该文件以显示多个列表,则需要创建如下内容:
List<String> generalFruits = new ArrayList<String>();
List<String> specificFruitX = new ArrayList<String>();
List<String> specificFruitY = new ArrayList<String>();
对于要在应用程序中显示的每个列表,您必须执行相同的操作
我希望它能对您有所帮助。不要创建一个包含50个的新数组(因为您可能会得到超过50个的数组),只需将文件中读取的每个项目附加到数组中即可。我不确定这是否准确,但请使用generalFruit.append(line);然后使用所有数组添加您读取的每一行。
generalFruits.add(new String(line));