我想读取一个URL,然后将其转换为字符串并将内容写入文本文件,但在编译代码时出现以下异常。这里是我的代码和我的例外:阅读URL时没有协议异常
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static String url = "google.com";
public static String fileName= null;
public static String fileConttent ="Something";
public static void main(String[] args) throws Exception {
getText(new String(url));
}
public static void getText(String url) throws Exception {
URL website = new URL("url\n" +
" public static void main(String[] args) throws Exception {\n" +
" getText(new String(url));\n" +
" }\n" +
"\n" +
" public static void getText(String url) throws Exception {\n" +
" URL website = new URL(\"url");
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
String toBeWritten = response.toString();
System.out.println(toBeWritten);
}
public static void createFile(String fileName,String fileContent){
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("C:\\Users\\Dell\\Documents\\t"+"fileName"), "utf-8"));
writer.write(fileContent);
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
}
这是我的例外:
Exception in thread "main" java.net.MalformedURLException: no protocol: url
at java.net.URL.<init>(URL.java:583)
at java.net.URL.<init>(URL.java:480)
at java.net.URL.<init>(URL.java:429)
at Main.getText(Main.java:15)
at Main.main(Main.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
过程与退出代码完成1
应该做些什么来解决这个问题?提前感谢所有答案。
更新
非常感谢你的回答。我做了你所说的,但我仍然得到同样的错误。
Exception in thread "main" java.net.MalformedURLException: no protocol: url
public static void main(String[] args) throws Exception {
getText(new String(url));
}
public static void getText(String url) throws Exception {
URL website = new URL("url
at java.net.URL.<init>(URL.java:583)
at java.net.URL.<init>(URL.java:480)
at java.net.URL.<init>(URL.java:429)
at Main.getText(Main.java:15)
at Main.main(Main.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
过程完成,退出代码为1
问题已解决谢谢 –
这真的学会阅读堆栈跟踪很好的做法。编译器通常会告诉你代码失败(或接近它)的行号。 –
@Israel如果你已经解决了这个问题,你能发表一个答案来解释解决方案是什么吗? – Zyerah