我想将目标文件中的信息加载到“Song”类型的数组中
public class Song {
String name;
String singer;
public void setName(String name) {
this.name = name;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getName() {
return name;
}
public String getSinger() {
return singer;
}
@Override
public String toString() {
return getName() + "\t" + getSinger() + "\n";
}
这就是我尝试阅读的方法,但它不起作用
private void loadFromObj(File f) {
ObjectInputStream ois = null;
FileInputStream fis = null;
try {
Song[] s = new Song[100];
Object obj;
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
while ((obj = ois.readObject()) != null) {
for (int i = 0; i < s.length; i++) {
s[i] = (Song) obj;
}
}
ois.close();
fis.close();
// refreshTable(s);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
目标文件包含每行有歌曲名称和艺术家名称的行,用空格“\ t”
分隔这是我如何将信息写入目标文件
private void writeToObj(File f, Song[] s) {
song
// array to write to file
ObjectOutputStream oos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < s.length; i++) {
oos.writeObject(s[i].toString());
oos.writeObject(null);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
添加&#34;实现java.io.Serializable&#34;在&#34;公共课宋&#34;。
之后对于使用ObjectInputStream,您的类需要从java.io.Serializable或java.io.Externalizable实现,并且文件必须从ObjectOutputStream创建。 对于使用
的解析文本文件byte[] encoded = Files.readAllBytes(Paths.get(path));
String file = new String(encoded, encoding);
并将字符串解析为您的对象:
String[] vars = file.split("\t");
Song song = new Song();
song.setName(vars[0]);
song.setArtist(vars[1]);