这些是由main方法调用的类的构造函数的内容。
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
控制台中的输出:
LOL
即使重复运行,文件内容仍保持不变。我的IDE是eclipse
答案 0 :(得分:1)
您将FileWriter
与boolean append
设置为false
进行参数设置。
因此,每次执行给定构造函数时都会写入相同的文件,并在其中打印"LOL"
。
在打印"LOL"
之前,Scanner
读取每一行并打印出来,因此我们系统中打印出LOL
。
另请注意,您可能希望从FileWriter
块中声明BufferedWriter
和try
,因此您可以在finally
块中刷新并关闭它们。
答案 1 :(得分:0)
这篇文章只包含初始问题,原因是所有内容都已更正,以避免与资源相关的多个错误。它假设Java 6或更低版本。
我不应该得到任何upvote所以请不要;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}