2013-08-06 114 views
0

如何从文本中读取行?看看我的代码:如何从txt读取行?

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

另外我有secnod版本,但我的服务器冻结。

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

我认为它不能关闭连接或什么。 即使我在尝试构建中说name="TEST";,它也会返回NULL。

+1

这可能会引发异常。不要像那样默默地消费例外。 – arshajii

+1

可能引发异常。在'catch'块中加入一些东西,比如'e.printStackException()'看看是否是这种情况。 –

+0

嗯。真。如果我尝试这个'catch(Exception e){ } \t \t \t \t \t \t name =“TEST”; \t \t}'它会返回“测试”。 –

回答

6

FileReader正是–从文件读取的类,而不是HTTP请求。

你得到一个无效的文件路径例外,你是那么你的邪恶空的catch块忽略。

相反,你应该使用URLConnection

0

试试这个

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

据我所知,URL#openStream()内部调用URL#openConnection()这就造成URLConnection一个实例,并调用它URLConnection#getInputStream()

+0

阅读器无法解析 –

+0

你是什么意思? –

+0

哦。我没有注意到。我会尽力。 –