在Java中读取.txt文件并将其保存到数组中
我目前正试图找出如何在Java中读取在Java中读取.txt文件并将其保存到数组中,java,arrays,Java,Arrays,我目前正试图找出如何在Java中读取.txt文件并将其保存到动态数组中,我不知道如何将读取的.txt文件保存到数组中。我试图读取的文件名为songCollection.txt 具体数据部分需要: title,artist,genre,album,songID 下面是我目前的代码,任何帮助都将不胜感激。谢谢 代码: 我不知道你到底在看什么。但如果您只是想在中存储数据,那么可以在ArrayList或任何适合您的集合中存储字符串数组。 如果以后要使用它进行快速检索,可以使用任何map实现来存储密钥和
.txt
文件并将其保存到动态数组中,我不知道如何将读取的.txt
文件保存到数组中。我试图读取的文件名为songCollection.txt
具体数据部分需要:
title,artist,genre,album,songID
下面是我目前的代码,任何帮助都将不胜感激。谢谢
代码:
我不知道你到底在看什么。但如果您只是想在中存储数据,那么可以在ArrayList或任何适合您的集合中存储字符串数组。 如果以后要使用它进行快速检索,可以使用任何map实现来存储密钥和值对问题:“我不知道如何将read.txt文件保存到数组中” 回答:
大多数文本文件都可以使用简单的
扫描仪
读入程序。例如:
Scanner input = new Scanner(fileName);
int[] ints = new int[10];
int i = 0;
while (input.hasNextInt()) {
input.nextInt() = ints[i];
i++
}
input.close()
这种方法的唯一问题是,您不知道需要多大的阵列。我建议您将输入存储在动态分配空间的数据结构中,如
链接列表
或无限堆栈
而不是将令牌打印到控制台,您应该创建一个新的歌曲实例并为其设置值:
song s = new song();
s.SongId = Integer.parseInt(splitOut[0]);
s.title = splitOut[1];
s.artist = splitOut[2];
...
然后将此歌曲实例放入列表
还考虑以所有这些字段为参数实现歌曲构造函数。
< P>您应该定义<代码>歌曲类的构造函数为:String temp = "";
try{
Scanner input = new Scanner("yourfile.txt");
while(input.hasNext()){
temp = temp + "_" + input.next();
}
input.close();
}
catch(Exception e){
}
String fin[] = temp.split("_");
public Song(int songId, String title, String artist, String genre,
String album, String songData) {
this.songId = songId;
this.title = title;
this.artist = artist;
this.genre = genre;
this.album = album;
this.songData = songData;
}
下面是一个使用BufferedReader
将所有歌曲行读入列表的示例(此代码需要Java7):
List songs=new ArrayList();//歌曲对象列表
try(BufferedReader输入=新建BufferedReader(新建InputStreamReader(
新文件输入流(“songCollection.txt”)、Charset.forName(“UTF-8”)){
弦线;
而((line=input.readLine())!=null){
字符串[]arr=line.split(“,”);
songs.add(新歌(Integer.parseInt(arr[0]),arr[1],arr[2],arr[3],
arr[4],arr[5]);//问题是,您如何知道需要多少元素?通过newscanner(fileSong);
您正在创建Scanner
而不是String[]
数组。此外,您可能应该使用新Scanner(new File(“yourFilePath”)
而不是空的fileSong
变量。
public Song(int songId, String title, String artist, String genre,
String album, String songData) {
this.songId = songId;
this.title = title;
this.artist = artist;
this.genre = genre;
this.album = album;
this.songData = songData;
}
List<Song> songs = new ArrayList<>(); // List of Song objects
try (BufferedReader input = new BufferedReader(new InputStreamReader(
new FileInputStream("songCollection.txt"), Charset.forName("UTF-8")))) {
String line;
while ((line = input.readLine()) != null) {
String[] arr = line.split(",");
songs.add(new Song(Integer.parseInt(arr[0]), arr[1], arr[2], arr[3],
arr[4], arr[5])); // <- Add new Song to list.
}
} catch (IOException e) {
e.printStackTrace();
}