【发布时间】:2026-02-10 14:50:02
【问题描述】:
我正在尝试实现一种将 Song() 对象数组写入文件以进行分配的方法。我对如何实现这一目标感到相当迷茫。我希望能够在 main 方法中调用该函数,但它似乎没有做任何事情。在这个阶段,这是一个测试,我希望它在运行 main() 时在命令行上打印。 这是我的代码:
public static void main (String[] args)
{ //run the main program.
Interface songUI = new Interface();
songUI.run();
try{
PrintWriter outputTest = null;
outputTest = write("testfile");
read();
}
catch(IOException e){
System.out.println("Caught!");
}
}
public static PrintWriter write (String fileName) throws IOException{
Scanner console = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(fileName);
outFile.println ("Random numbers");
for(int i=0; i<10; i++)
{
outFile.println ((int)( 1 + Math.random()*10) + " ");
}
outFile.close();
return outFile;
}
我还有一种方法可以从我试图在这里工作的文件中读取:
public static void read() throws IOException{
String fileName = "test1";
System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
Scanner inputStream = new Scanner (new File (fileName));
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
如您所知,我很困惑,任何帮助都会令人惊叹。谢谢。
【问题讨论】:
标签: java file file-io exception-handling io