gpt4 book ai didi

java - 将行写入输出文件(java)后尝试打印它们

转载 作者:行者123 更新时间:2023-12-01 14:02:48 25 4
gpt4 key购买 nike

我有一个问题。我基本上被要求使用一种方法从输出文件进行打印。因此,首先,我实际上开始用行填充输出文件......然后,当我尝试实际读取它们并将它们打印在屏幕上时,出现了一个小问题。我实际上使用了“调试”选项,问题出在“line = input.nextLine()”代码行内,但我真的不知道为什么......我的意思是这就是我们从输出中读取的方式文件...帮助将不胜感激。

这是我迄今为止的工作:

import java.util.*;
import java.io.*;

public class Problem_3 {

public static void main(String[] args) {

PrintWriter outFile = null;
File f1 = new File("try.txt");


try {

outFile = new PrintWriter("try.txt");
outFile.println("First line!");
outFile.println("Second line!");
outFile.println("Third line!");

cat(f1);
} catch (Exception e) {
outFile.print("(1) Exception: " + e.getMessage()); // no such element exception
}

outFile.close();
}
/*
* outFile = new PrintWriter(f1); outFile.println("Line 1");
* outFile.println("Line 2"); outFile.println("Line 3"); outFile.print("");
* cat(f1); } catch (Exception e) { System.out.println("(1)Exception: " +
* e.getMessage()); } outFile.close(); }
*/

public static void cat(File file) throws FileNotFoundException {

Scanner input = null;
String line = "";

input = new Scanner(new FileReader(file));
//line = input.next();
// line = input.nextLine();// this line calls the exception in the main method

while ((line != null)) {
System.out.println("In the while loop");
System.out.println("Line 323" + line);
return;
}
input.close();
}
}

最佳答案

修改代码为:

try {

outFile = new PrintWriter("try.txt");
outFile.println("First line!");
outFile.println("Second line!");
outFile.println("Third line!");

outFile.close();


}
catch (Exception e) {
outFile.print("(1) Exception: " + e.getMessage()); // no such element exception
}

cat(f1);

关闭文件之前您无法读取所写内容。

关于java - 将行写入输出文件(java)后尝试打印它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209635/

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