此代码:
String file = "";
String filename = "";
try{
BufferedReader ins = new BufferedReader(new FileReader(new File("filename.txt")));//get file name
while (ins.ready()) {
filename = ins.readLine();
}
ins.close();
}catch(Exception e){
}
String[] sa = filename.split("/");
file = sa[sa.length - 1];
try {
System.out.println(filename);
} catch (Exception e) {
e.printStackTrace();
}
打印:
http://wordpress.org/plugins/about/readme.txt
当我尝试做的时候:
URL url = new URL(filename);
我收到格式错误的网址例外:没有协议 这是无缘无故的。如果我手动将文件名字符串分配给 “http://wordpress.org/plugins/about/readme.txt”它会完美运行,文件阅读器有问题吗?
事情就像
从文件中读取一个字符串,然后将其设为URL!停止编辑错误!
答案 0 :(得分:1)
一个想法:
可能是文件以UTF-8保存,但文件开头有额外的BOM字符。这是一个零宽度的Unicode空间。
filename = filename.replaceFirst("^\uFFFE", "");
答案 1 :(得分:-2)
工作代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class MyFileReader {
public static void main(String[] args) {
String file = "";
String filename = "";
try {
BufferedReader ins = new BufferedReader(new FileReader(new File("c:\\filename.txt")));// get file name
while (ins.ready()) {
filename = ins.readLine();
}
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
String[] sa = filename.split("/");
file = sa[sa.length - 1];
try {
System.out.println(filename);
URL url = new URL(filename);
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
filename.txt的内容:
http://wordpress.org/plugins/about/readme.txt
程序输出:
http://wordpress.org/plugins/about/readme.txt
readme.txt
错误/异常: 的无强>