打开文件并存储消息。将消息读入字符串变量以打印。Java/Netbeans
嘿,我正在做的这个练习需要一些帮助。我必须打开一个名为hello.txt的文件,然后存储信息hello World!在文件中。然后我必须关闭文件并打开它,然后将消息读入字符串变量以打印它。到目前为止,我有以下代码。你对我如何成功编译这段代码有什么建议吗打开文件并存储消息。将消息读入字符串变量以打印。Java/Netbeans,java,input,netbeans,output,Java,Input,Netbeans,Output,嘿,我正在做的这个练习需要一些帮助。我必须打开一个名为hello.txt的文件,然后存储信息hello World!在文件中。然后我必须关闭文件并打开它,然后将消息读入字符串变量以打印它。到目前为止,我有以下代码。你对我如何成功编译这段代码有什么建议吗 package ProgrammingExercise11; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; impo
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();
}
}
Java7之后的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();
}
}
好的,让我们回答你的问题
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();
您的代码无法编译,因为您在中引入了两个同名变量,并且没有声明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世界 如果您的代码未编译,请告诉我们编译器给您的错误消息。