Java 写入器在单次写入后停止
Java Writer stopping after single write
我想读取 URL 的内容并将它们写入文件,这按预期工作,但它只写入一次,即使程序控制台显示多行。
代码:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(true) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.close();
URL 中的数据不断刷新,因此每次应该有不同的数据,如控制台打印所示,但它只是将第一个实例写入文件。
关键是writer.close()
!如果你想每次都重新写入文件,你必须每次重新打开Writer
。
如果你想每次都追加文件,你必须刷新写入器而不是关闭并在最后关闭。
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(condition) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.flush();
}
writer.close();
我想读取 URL 的内容并将它们写入文件,这按预期工作,但它只写入一次,即使程序控制台显示多行。
代码:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(true) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.close();
URL 中的数据不断刷新,因此每次应该有不同的数据,如控制台打印所示,但它只是将第一个实例写入文件。
关键是writer.close()
!如果你想每次都重新写入文件,你必须每次重新打开Writer
。
如果你想每次都追加文件,你必须刷新写入器而不是关闭并在最后关闭。
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(condition) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.flush();
}
writer.close();