我已经被要求将当前程序保存到文件中,以便以后即使程序结束也可以继续。但是我是java的新手,所以如果有人可以帮助我,我真的很感激:)这是我设法完成的代码,但是它只是创建一个空文件,我怎么想去解决这个问题呢? / p>
以下不是整个程序编码,我只是复制了相关的代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileWriter;
public static void main (String[] param) throws FileNotFoundException
{
try
{
fileinputoutput ();
}
catch (FileNotFoundException e)
{
System.exit(0);
}
} // END main
public static void fileinputoutput() throws FileNotFoundException
{
File input = new File("input.txt");
File output = new File("loveletter.txt");
PrintWriter outputFile = new PrintWriter(output);
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputfile = new File(filename);
Scanner newfile = new Scanner(inputfile);
newfile.close();
while(newfile.hasNext())
{
String write = newfile.nextLine();
System.out.println(write);
}
outputFile.close();
}
答案 0 :(得分:1)
答案非常明显。你只得到一个空白文件的原因是你从来没有通过outputFile
写任何东西并关闭newfile
之前你可以做任何事情。你应该尝试这样的事情:
public static void fileinputoutput() throws FileNotFoundException {
File input = new File("input.txt"); // What do you use this variable for? It's never used in the code fragment you posted
File output = new File("loveletter.txt");
PrintWriter outputFile = new FileWriter(output); // I'd personally use FileWriter here
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputFile = new File(filename);
Scanner newfile = new Scanner(inputFile);
while(newfile.hasNext()) {
String write = newfile.nextLine();
outputFile.println(write); // You used to only output something to the console here
}
outputFile.close();
newfile.close();
check.close();
}