1) класс получает данные (xml файл) из интернета:
| Код | import org.xml.sax.*; import java.net.*; import java.io.*;
public class BookCounter extends HandlerBase{
private int count = 0; public float g_CourseUSD; public float g_CourseEuro;
public static void main( String args[] ) throws Exception { System.getProperties().put( "proxyHost","192.168.18.1" ); System.getProperties().put( "proxyPort", "8080" ); URL l_test = new URL("http://www.cbr.ru/scripts/XML_daily.asp");
BufferedReader br = new BufferedReader( new InputStreamReader(l_test.openStream())); String line = null; FileWriter l_FileW = new FileWriter( "daily_courses.xml" ); int i=0; while ((line = br.readLine()) != null ){ if (i>0){ l_FileW.write( line +"\r\n"); } else { l_FileW.write( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"); } i++; } br.close(); l_FileW.close();
String inEncoding = "Cp1251", outEncoding = "UTF-8"; Reader reader = new InputStreamReader(new FileInputStream("daily_courses.xml"), inEncoding); Writer writer = new OutputStreamWriter(new FileOutputStream("daily_courses1.xml"), outEncoding); char[] buffer = new char[16 * 1024]; int read; while((read = reader.read(buffer)) != -1){ writer.write(buffer, 0, read); } reader.close(); writer.close(); (new BookCounter() ).countBooks(); } public void countBooks() throws Exception { Parser p = new com.jclark.xml.sax.Driver(); p.setDocumentHandler(this);
String l_File = "file:///"+System.getProperties().getProperty("user.dir")+"\\daily_courses1.xml"; p.parse( l_File ); } public void startElement(String name, AttributeList atts) throws SAXException { if (name.equals("book")) count++; } public void endDocument() throws SAXException {
} }
|
пробую класс запустить через командную строку, - получаю, что из инета стягиваю файл и сохраняю на диске, чего в принципе и надо было добиться.
2) отображаю форму. хочу чтобы она при этом запускала первый класс, чтобы он стягивал файл из интернета.
| Код | import java.awt.*; import javax.swing.*;
class NewFrame extends JFrame{ NewFrame(){ super("gdsfgdf"); BookCounter l_Test = new BookCounter(); try{ l_Test.countBooks(); } catch(Exception e){ TextField l_Label = new TextField( e.toString(), 30 ); l_Label.setBounds(10, 50, 100, 100); add( l_Label ); } setBackground(Color.WHITE); setSize(800,200); setVisible(true); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
public static void main( String args[] ){ new NewFrame(); } }
|
форма запускается и выдаёт ошибку:
| Цитата | | java.io.FileNotFoundException: E:\Java\daily_courses1.xml (Не удается найти указанный файл) |
если класс BookCounter запускается, то почему он не закачивает файл? |