0

这段代码:

        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);

我收到格式错误的 URL 异常:无协议 这是无缘无故发生的。如果我手动将文件名字符串分配给“ http://wordpress.org/plugins/about/readme.txt ”,它将完美运行,文件阅读器是否有问题?

事情是这样的

从文件中读取一个字符串,然后将其设为 URL!停止错误编辑!

4

2 回答 2

1

一个想法:

可能是文件以 UTF-8 保存,但文件开头有一个额外的 BOM 字符。这是一个零宽度的 Unicode 空间。

filename = filename.replaceFirst("^\uFFFE", "");
于 2014-02-18T16:35:25.910 回答
-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

错误/异常:

于 2014-02-18T16:08:36.203 回答