我在使用I / O时遇到了一些麻烦。我有一个名为SongTextFileProcessor的类,它应该处理一个Song对象(在Song类中定义)与文件的读/写。这是我的写法:
@Override
public void writeSong(String songName, String fileName)
{
String [] songObject = songName.split(", ");
Song s1 = new Song (songObject[0], songObject[1], songObject[2]);
try
{
PrintWriter output = new PrintWriter (new File (fileName));
output.print(s1.printSong());
output.close();
}
catch (Exception e)
{
System.out.println("Exception caught.");
}
}
我的阅读方法:
@Override
public void readSong(String fileName)
{
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
}
catch (Exception e)
{
System.out.println("Exception caught.");
}
}
但是,当我尝试使用以下代码从Test类调用这些方法时:
String songName = "Maad City, Kendrick Lamar, Hip-Hop";
String fileName = "songs.txt";
writeSong(songName, fileName);
readSong(fileName);
它给了我错误"方法writeSong(String,String)未定义类型Test"。这使我感到沮丧,因为我熟悉Java I / O,并且熟悉Java,当这两个方法都从Test类中调用时,它们完美地工作,这意味着问题必须在传递过程中SongTextFileProcessor中方法的参数。有什么想法吗?
这是歌曲课程:
public class Song
{
private String title, artist, genre;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getArtist()
{
return artist;
}
public void setArtist(String artist)
{
this.artist = artist;
}
public String getGenre()
{
return genre;
}
public void setGenre(String genre)
{
this.genre = genre;
}
public Song(String title, String artist, String genre)
{
this.title = title;
this.artist = artist;
this.genre = genre;
}
public String printSong()
{
return (getTitle() + " by " + getArtist() + " is a " + getGenre() + " song.");
}
}
The readSong and writeSong methods are the only methods in the SongTextFileProcessor class, and both of those methods are defined by Interfaces. And i've shown all the code I have in the Test class.
答案 0 :(得分:0)
在文本课中尝试:
String songName = "Maad City, Kendrick Lamar, Hip-Hop";
String fileName = "songs.txt";
SongTextFileProcessor stfp = new SongTextFileProcessor ();
stfp.writeSong(songName, fileName);
stfp.readSong(fileName);