嘿,我正在进行的这项练习需要一些帮助。我必须打开一个名为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();
}
}
好,让我们回答您的问题。
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世界!
自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();
}
}