简体   繁体   中英

How to read line from txt?

How can I read line from text? Look at my code:

public static String getTemplateFromFile() {
        String name = null;
        try {
            BufferedReader reader = new BufferedReader(new 
                        FileReader(
                      "http://localhost:8080/blog/resources/cache/templateName.txt"));
            name = reader.readLine();
            //name="TEST";
            //NULL anyway
            reader.close();

        }

        catch (Exception e) {

        }


        return name;
    }

Also I have got secnod version, but my server freeze.

public static String getTemplateFromFile() {
        String name = null;
        /*
        try {
               URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
               Scanner s = new Scanner(url.openStream());   

               name=s.nextLine();
               s.close();
            }
            catch(IOException ex) {

               ex.printStackTrace();
            }*/
        return name;
    }

I think it can't close connection or something. It returns me NULL even I say name="TEST"; in try construction.

FileReader is exactly that – a class that reads from files , not HTTP requests.

You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.

Instead, you should use URLConnection .

Try this

try{
     URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
     BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
     name = br.readLine();
     //name="TEST";     
     br.close();
}catch (MalformedURLException ex) {
         ex.printStackTrace();
} catch (IOException ex) {
         ex.printStackTrace();
}

AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM