2016-03-02 39 views
0

我想要做的就是让这个网址的内容:如何将URL中的xml数据保存到文件中?

https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=CYQB&hoursBeforeNow=2

并将其复制到文件中,以便我可以分析它,并使用的元素。

这是我到目前为止有:

package test; 

import java.io.*; 
import java.net.*; 

import org.apache.commons.io.FileUtils; 

public class JavaGetUrl { 

@SuppressWarnings("deprecation") 
public static void main(String[] args) throws FileNotFoundException { 

    URL u; 
    InputStream is = null; 
    DataInputStream dis; 
    String s = null; 

    try { 

     u = new URL(
       "https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=CYQB&hoursBeforeNow=2"); 

     is = u.openStream(); // throws an IOException 

     dis = new DataInputStream(new BufferedInputStream(is)); 

     while ((s = dis.readLine()) != null) { 
      System.out.println(s); 
      FileUtils.writeStringToFile(new File("input.txt"), s); 
     } 

    } catch (MalformedURLException mue) { 

     System.out.println("Ouch - a MalformedURLException happened."); 
     mue.printStackTrace(); 
     System.exit(1); 

    } catch (IOException ioe) { 

     System.out.println("Oops- an IOException happened."); 
     ioe.printStackTrace(); 
     System.exit(1); 

    } finally { 

     try { 
      is.close(); 
     } catch (IOException ioe) { 

     } 

    } 

} 
} 

的问题是,S含量不input.txt中露面。

如果我用任何其他字符串替换它的工作。所以我想这是s的数据有问题。是因为它是xml吗?

谢谢大家的帮助。

回答

3

该文件可能会被覆盖。

您应该使用“append”mode来获取附加了数据(来自readLine)的文件。

public static void writeStringToFile(File file, 
           String data, 
           boolean append) 
相关问题