-4

嘿,我正在做的这个练习需要一些帮助。我必须打开一个名为 hello.txt 的文件,然后存储消息“Hello World!” 在文件中。然后我必须关闭文件并打开它,并将消息读入字符串变量以打印它。到目前为止,我在下面有这段代码。您对我如何成功编译此代码有任何建议吗?

package ProgrammingExercise11;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Input {

    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner in = new Scanner(System.in);
        File inputFile = new File(hello.txt);
        Scanner in = new Scanner(inputFile);
        PrintWriter out = new PrintWriter(hello.txt);
        out.println("Hello, World!");
        String line = in.nextLine();
        in.close();
        out.close();
    }

}
4

2 回答 2

2

好的,我们来回答你的问题。

Scanner in = new Scanner(System.in);
        File inputFile = new File(hello.txt);
        Scanner in = new Scanner(inputFile);
        PrintWriter out = new PrintWriter(hello.txt);
        out.println("Hello, World!");
        String line = in.nextLine();
        in.close();
        out.close();

您的代码无法编译,因为您引入了两个具有相同名称的变量in并且您没有声明hello.txt. 按照你的想法解决它。

 public static void main(String[] args) throws Exception {
            String filePath = "hello.txt";
            File inputFile = new File(filePath);

            PrintWriter printWriter = new PrintWriter(inputFile);
            printWriter.write("Hello World!");
            printWriter.close();

            InputStream is = new FileInputStream(inputFile.getPath());
            BufferedReader buf = new BufferedReader(new InputStreamReader(is));
            String line = buf.readLine();
            System.out.println(line);

            is.close();
            buf.close();

    }

欢迎来到 Java 世界!

于 2020-05-08T08:09:41.240 回答
0

从 Java 7 开始的 Files 类提供了对文件、目录或其他类型文件进行操作的静态方法,更加简单灵活。

String file = "hello.txt";
Path filePath = Paths.get(file);
if (Files.isRegularFile(filePath)) {
    try(OutputStream fos = new FileOutputStream(file);
        InputStream fis = new FileInputStream(file)){
        // write message to file.
        String message = "Hello World!";
        byte[] messageBytes = message.getBytes();
        fos.write(messageBytes);

        // read message from file.
        byte[] receivedBytes = new byte[fis.available()];
        fis.read(receivedBytes);
        System.out.println(new String(receivedBytes));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
于 2020-05-08T07:44:54.180 回答