[英]Trouble with Java File I/O?
我在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);
它給我一個錯誤:“類型Test的方法writeSong(String,String)未定義”。 這讓我感到沮喪,因為我熟悉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.
在文本類中嘗試一下:
String songName = "Maad City, Kendrick Lamar, Hip-Hop";
String fileName = "songs.txt";
SongTextFileProcessor stfp = new SongTextFileProcessor ();
stfp.writeSong(songName, fileName);
stfp.readSong(fileName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.