2012-06-07 2 views
1

나는 URL를 명중하고 연결을 창조하고 파일을 쓰고 SDcard에 저장해야하는 검은 딸기 신청에 종사하고있다. 현재이 특정 코드를 따르고 있습니다. 그러나 FileOutputStream 객체를 생성하는 동안 CLassCastException을 발생시킵니다. 나는 이것으로 고투하고있다.검은 딸기에있는 주어진 URL에서 pdf 파일을 다운로드하십시오

public void run() { 
      HttpConnection httpConnection = null; 
      DataOutputStream httpDataOutput = null; 
      InputStream httpInput = null; 
      OutputStream fos=null; 
      int rc; 
      try { 
       httpConnection = new HttpConnectionFactory() 
       .getHttpConnection("http://faultcode.techvalens.net/PDF/DrawingSample.PDF"); 
       rc = httpConnection.getResponseCode(); 
       if (rc != HttpConnection.HTTP_OK) { 
        throw new IOException("HTTP response code: " + rc); 
       } 
       httpInput = httpConnection.openInputStream(); 
       InputStream is = httpInput; 

       FileConnection fconn=(FileConnection)Connector.open("file:///SDCard/Test.txt", 
         Connector.READ_WRITE); 
       if(!fconn.exists()) 
        fconn.create(); 
       System.out.println(fconn.exists()); 

       fos = new FileOutputStream(File.FILESYSTEM_PATRIOT, "Test.txt"); 
      // byte[] b = IOUtilities.streamToBytes(inp); 

       byte[] buffer = new byte[702]; 
        int len1 = 0; 
        while ((len1 = is.read(buffer)) != -1) { 
         fos.write(buffer, 0, len1); 
        } 

      } catch (Exception ex) { 
       System.out.println("URL Error........" + ex.getMessage()); 
      } finally { 
       try { 
        if (httpInput != null) 
         httpInput.close(); 
        if (httpDataOutput != null) 
         httpDataOutput.close(); 
        if (httpConnection != null) 
         httpConnection.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 

       } 
      } 
     } 

위의 코드를 사용하고 있습니다. 실수가 무엇인지 알려주세요. 고맙습니다 ... !!!

+1

필자는 왜 FileOutputStream이 필요한지 이해하지 못합니다. 그냥 fconn.openOutputStream()을 호출하고 원하는대로 바이트를 씁니다. 또한 마지막으로 파일 연결과 스트림을 닫는 것을 잊지 마십시오! FileOutputStream에 관해서 - javadoc에는 두 가지가 있습니다. 여기서는 캐스팅이 보이지 않지만 아마도 RIM 프레임 워크에서는 어떤 일이 일어날 것입니다. 또한 javadoc은 iDEN 파일 시스템에 대해 뭔가를 말합니다. 이 파일 시스템을 모르지만 iDEN 장치는 Sprint 장치의 일부이며 모든 BlackBerry 장치를 전혀 포함하지 않습니다. –

답변

0

이 작업은 기본 작업 이었지만 나를 잊을 수없는 개념으로 만들었습니다. 아래 코드는 현재 사용하고 있습니다. URL에서 모든 유형의 파일을 다운로드해야하는 경우 가장 좋습니다.

public void run(){ 
     GetURLWebService _webService = new GetURLWebService(methodName,elecID,pdfType,performedBy,notes); 
     String pdfURL = _webService.getWebServiceData(); 
     _pdfURL = pdfURL; 

     System.out.println("Download the pdf...!!!"); 
     try { 
      int chunkIndex = 0; 
      int totalSize = 0; 
      /* 
      * File connection 
      */ 
      FileConnection file =(FileConnection)Connector.open(localFile); 
      if (!file.exists()) { 
       file.create(); 
      } 
      file.setWritable(true); 
      OutputStream out = file.openOutputStream(); 
      /* 
      * HTTP Connections 
      */ 
      String currentFile = _pdfURL + connectionType(); 
      //log("Full URL: " + currentFile); 
      HttpConnection conn; 
      InputStream in; 
      int rangeStart = 0; 
      int rangeEnd = 0; 
      while (true) { 
       // log("Opening Chunk: " + chunkIndex); 
       conn = (HttpConnection) Connector.open(currentFile, 
         Connector.READ_WRITE, true); 
       rangeStart = chunkIndex * chunksize; 
       rangeEnd = rangeStart + chunksize - 1; 
       // log("Requesting Range: " + rangeStart + 
       //  "-" + rangeEnd); 
       conn.setRequestProperty("Range", "bytes=" + 
         rangeStart + "-" + rangeEnd); 
       int responseCode = conn.getResponseCode(); 
       if (responseCode != 200 && responseCode != 206) 
       { 
        // log("Response Code = " + conn.getResponseCode()); 
        break; 
       } 
       // log("Retreived Range: " + conn.getHeaderField("Content-Range")); 
       in = conn.openInputStream(); 
       int length = -1; 
       byte[] readBlock = new byte[256]; 
       int fileSize = 0; 
       while ((length = in.read(readBlock)) != -1) { 
        out.write(readBlock, 0, length); 
        fileSize += length; 
        Thread.yield(); // Try not to get cut off 
       } 
       totalSize += fileSize; 
       // log("Chunk Downloaded: " + fileSize + " Bytes"); 
       chunkIndex++; // index (range) increase 
       in.close(); 
       conn.close(); 
       in = null; 
       conn = null; 
       /* 
       * Pause to allow connections to close and other Threads 
       * to run. 
       */ 
       Thread.sleep(1000); 
      } 
      // log("Full file downloaded: " + totalSize + " Bytes"); 
      out.close(); 
      file.close(); 
      // log("Wrote file to local storage"); 
     } catch (Exception e) { 
      System.out.println(e.toString()); 
     } 
    } 
    private String connectionType() { 
     switch (conn) { 
     case 1: 
      return ";deviceside=false"; 
     case 2: 
      return ";deviceside=true;interface=wifi"; 
     default: 
      return ";deviceside=true"; 
     } 
    } 
+0

나도 이것을 개선해야 할 필요가 있다면 알려줘. Coz 내가 최고 일 필요가있어 :) –

관련 문제