0

私はURLからファイルをダウンロードしてフォルダに入れる多くの方法を試してきました。

public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}

boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
    try {
        saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
    } catch (MalformedURLException ex) {
        Status.setText("MalformedURLException");
        Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Status.setText("IOException Error");
        Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
    }

このコードをネットで見つけましたが、正しく使用していますか?

私がやった場合:saveFile( "FolderName"、 "ADirectDownloadLinkForAFile")

IOExceptionエラーが発生します

私のコードに実行させたいのは次のとおりです。

  1. フォルダーを作る
  2. ダウンロードファイル
  3. 作成したフォルダに移動するためにファイルをダウンロードしました

申し訳ありませんが、ここでは初心者です。助けてください

4

2 に答える 2

1

Java でインターネットからファイルをダウンロードするには、さまざまな方法があります。最も簡単な方法は、バッファとストリームを使用することです:

File theDir = new File("new folder");

  // if the directory does not exist, create it
  if (!theDir.exists())
  {
    System.out.println("creating directory: " + directoryName);
    boolean result = theDir.mkdir();  
    if(result){    
       System.out.println("DIR created");  
     }

  }
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
        while((count = in.read(data,0,1024)) != -1)
        {
            out.write(data, 0, count);
        }

まさに基本コンセプト。ストリームを閉じることを忘れないでください;)

于 2013-02-04T14:02:20.833 に答える
0

File.mkdirs()ステートメントは というフォルダーを作成しているように見えますがFilessaveFile()メソッドはこれを使用しておらず、単に現在のディレクトリにファイルを保存しているようには見えません。

于 2013-02-04T14:01:25.733 に答える