需要java IO类的帮助吗
我需要一个IO java代码的帮助,我正在尝试将java控制台输出[从URL类]保存到本地机器中的一个文件,我能够获得输出,需要帮助将该文件保存到本地机器 为了得到输出,我做了如下编码需要java IO类的帮助吗,java,java-io,Java,Java Io,我需要一个IO java代码的帮助,我正在尝试将java控制台输出[从URL类]保存到本地机器中的一个文件,我能够获得输出,需要帮助将该文件保存到本地机器 为了得到输出,我做了如下编码 import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL oracle = n
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.yahoo.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
注意:我有另一个代码,在其中我可以将输出保存到一个文件中,但无法将两者关联起来,我尝试了扩展,但并没有进展,下面是该类
import java.io.*;
class FileWrite {
public static void main(String args[]) {
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
它实际上几乎都在那里,你只需要知道每行代码都做了什么,就可以知道如何将它们组合在一起
import java.net.*;
import java.io.*;
public class WriteFromURL {
public static void main(String[] args) throws Exception {
try{
// Block from connection reader
URL oracle = new URL("http://www.yahoo.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
// Block from writer
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
// Block from reader w/ small change
String inputLine;
while ((inputLine = in.readLine()) != null){
// Write what you read
out.write(inputLine);
out.newLine();
}
in.close();
// Block from writer
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
您正在将文本输出到控制台,为什么不将其写入文件
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
String inputLine;
while ((inputLine = in.readLine()) != null){
out.write(inputLine);
System.out.println(inputLine);
}
out.close();
in.close();
}
}
现在,两个代码部分连接在一起,以实现您想要的功能。我没有运行代码。检查其正确性,并添加错误处理代码。这就是您的代码的真实外观吗?你一点缩进都没有吗?你的代码很难读懂。他们把Shift键放在键盘上是有原因的。这样你就不用一直喊了。当你大声喊叫时,你的问题就更难理解,很烦人,而且也不会让你更快得到答案。(同样,你的问题对你来说可能很重要,但其他人的问题对你来说也很重要。请求紧急或尽快的帮助只会把你的问题弄得乱七八糟。只需在没有紧急请求的情况下提问,就会有人尽快帮你。)在写作部分,举个例子:我在想如何对你说thx(真实性)。你是我的救命恩人。@Satyam:把答案标记为已接受的答案来表示感谢。有关更多信息,请参阅。非常感谢您花费的时间和精力