我目前有一个数据库访问类来从列表中提取数据,如下所示:
Pique:CBPique.png:41:22:55:91
Ronaldo:STRonaldo.png:89:85:92:91
...
课程如下:
class DatabaseAccess {
static DatabaseAccess dataAccessor;
static DatabaseAccess getInstance(String dbPath) {
if (dataAccessor == null) {
dataAccessor = new DatabaseAccess(dbPath);
}
return dataAccessor;
}
private DatabaseAccess(String dbPath) {
dbLocation = dbPath;
}
List<FootballPlayer> getCards() {
return this.getData();
}
private List<FootballPlayer> getData() {
List<FootballPlayer> theData = new ArrayList<FootballPlayer>();
// create a Scanner and grab the data . . .
Scanner scanner = null;
String dataPath = dbLocation + File.separator + "text" + File.separator + "players.db";
String imagePath = dbLocation + File.separator + "images";
try {
scanner = new Scanner(new File(dataPath));
} catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
System.exit(0);
}
// scan players.db file line-by-line
scanner.useDelimiter("\n");
while (scanner.hasNext()) {
String line = scanner.next().trim();
// trim used to trim for new line
String[] bits = line.split(":");
String t = bits[0]; // title
String imgFileName = bits[1]; // image file name
int pa = Integer.parseInt(bits[2]); // pace
int sh = Integer.parseInt(bits[3]); // shooting
int dr = Integer.parseInt(bits[4]); // dribbling
int ph = Integer.parseInt(bits[5]); // physical
// create the image
ImageIcon img = new ImageIcon(imagePath + File.separator + imgFileName);
// Create the business object
FootballPlayer player = new FootballPlayer(t, img, pa, sh, dr, ph);
// add it to the list ... simple as ...
theData.add(player);
}
scanner.close();
return theData;
}
我想要做的是从此列表中提取数据并在另一个类中显示/使用它,例如拉动图像文件名以供使用,甚至在列表中显示所有数据。
一直在努力,任何帮助都会非常感激。
答案 0 :(得分:1)
这可能是您的扫描仪可能的样子:它读取文件并将每行的行保存到ArrayList中。
ArrayList<String> singleParts = new ArrayList<String>();
try {
int index = 0;
Scanner scanner = new Scanner( new File("files/"+filename+".txt") );
while ( scanner.hasNextLine() ) {
String actualLine = scanner.nextLine();
singleParts.add(actualLine);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(Throwable te) {
te.printStackTrace();
}
在此之后,您可以遍历每行的ArrayList行,char per char。为了方便起见,您可以使用&#39;:&#39;作为一个分离者。
第一行示例,名称:
String name = "";
boolean saved = false;
for(int line = 0; line < singleParts.size(); line++) {
for(int char = 0; char < singleParts.get(line).length(); char++) {
if(char<singleParts.get(line).indexOf(':') {
name += singleParts.get(line).charAt(char);
}
}
}
要完成剩下的工作,你有很多可能性。例如,删除已经使用的字符并重用类似于此的循环。
答案 1 :(得分:1)
您的Player对象是否具有唯一的属性/属性,例如名称或ID?
由于您已经拥有包含所需属性的Player
对象,为什么不将其放在HashMap
而不是Arraylist
中,考虑您是否有密钥< / strong>标识具体的Player
?
FootballPlayer player = new FootballPlayer(t, img, pa, sh, dr, ph);
yourKey = t // an identifier to you player, in this case i used t for example
playersMap.put(t,player);
这样您就可以使用
轻松检索您的播放器Player myPlayer = playersMap.get(yourKey)
// you can then get the properties of the Player
myPlayer.getImg();
myPlayer.getPa();
希望这有帮助