gpt4 book ai didi

java - 文件输入/输出

转载 作者:行者123 更新时间:2023-12-01 12:09:12 24 4
gpt4 key购买 nike

有人要求我将当前的程序保存到一个文件中,以便以后即使程序结束也可以继续。不过我是java新手,所以如果有人可以帮助我,我将非常感激:)这是我设法完成的代码,但它只是创建一个空文件,我该如何解决这个问题?

下面不是整个程序编码,我只是复制了相关的代码。

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();

}

最佳答案

答案很明显。您只得到一个空白文件的原因是您从未通过 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();
}

关于java - 文件输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com