如何提示用户为写入和读取序列化文件指定名称?

时间:2014-09-22 04:05:49

标签: java serialization

我试图提示用户为写入和读取序列化文件创建名称。例如。我可以做以下事情:

System.out.print("What would you like to name your file?");
String fileName = scanner.nextLine;

try{
 ObjectOutput ostream = new ObjectOutputStream(new FileOutputStream(fileName)) // Would this create a file with the name inputted by the user? If so what would be the extension for the file?

 ostream.writeObject(//whatever I want to put in here)

 //close

//catch

try{

 ObjectInputStream = new ObjectInputStream(new FileInputStream(fileName))

//catch

1 个答案:

答案 0 :(得分:0)

如果您想从终端提示用户提供某些内容,最简单的方法可能是使用java.io.Console,特别是其readLine()方法之一:

import java.io.Console;

...

Console console = System.console();
if (console == null) {
  throw new IllegalStateException("No console to read input from!");
}

String fileName = console.readLine("What would you like to name your file? ");
// Whatever the user inputed is now in fileName

请参阅http://docs.oracle.com/javase/7/docs/api/java/io/Console.html