【问题标题】:Save input stream in local path将输入流保存在本地路径中
【发布时间】:2014-03-14 18:31:26
【问题描述】:

我正在尝试点击 URL 并尝试将 XML 文件保存到本地路径,但我无法做到。

我使用的代码在这里

公共类 T_save { 公共静态无效下载(字符串地址,字符串本地文件名){ 输出流输出 = null; URLConnection 连接 = 空; InputStream in = null;

    try {
       URL url = new URL("url");
    //  URL url = new URL(address);
        conn = url.openConnection();
        in = conn.getInputStream();
        File file = new File(address+localFileName);
        FileWriter fileWriter = new FileWriter(file);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            fileWriter.write(line);
        }
        fileWriter.flush();
        fileWriter.close();

    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
        }
    }
}

public static void download(String address) {
    int lastSlashIndex = address.lastIndexOf('\');
    if (lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1) {
        System.out.println(address.substring(0, lastSlashIndex+1)+"\t\t\t"+ 

  address.substring(lastSlashIndex + 1));
        download(address.substring(0, lastSlashIndex+1), address.substring

     (lastSlashIndex + 1));

    } else {
        System.err.println("Could not figure out local file name for "
                + address);
    }
}

public static void main(String[] args) {

    download("C:\\Users\\praveen\\chaithu12.xml");}
    /*
     * for (int i = 0; i < args.length; i++) { download(args[i]); }

     */
 public static class CustomAuthenticator extends Authenticator {



    // for entering password

    protected PasswordAuthentication getPasswordAuthentication() {



        // Get information about the request

        String prompt = getRequestingPrompt();

        String hostname = getRequestingHost();

        InetAddress ipaddr = getRequestingSite();

        int port = getRequestingPort();



        String username = "username";

        String password = "password";



        // Return the information (a data holder that is used by Authenticator)

        return new PasswordAuthentication(username, password.toCharArray());



    }
}
     }

【问题讨论】:

  • 有没有其他方法可以将输入流保存到本地路径的xml文件中
  • 还有其他方法吗??

标签: xml


【解决方案1】:

你可以这样做

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class T_save {
    public static void download(String address, String localFileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;

        try {
            URL url = new URL("http://www.w3schools.com/");
        //  URL url = new URL(address);
            conn = url.openConnection();
            in = conn.getInputStream();

            File file = new File(address+localFileName);
            FileWriter fileWriter = new FileWriter(file);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileWriter.write(line);
            }
            fileWriter.flush();
            fileWriter.close();

        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }

    public static void download(String address) {
        int lastSlashIndex = address.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1) {
            System.out.println(address.substring(0, lastSlashIndex+1)+"\t\t\t"+ address.substring(lastSlashIndex + 1));
            download(address.substring(0, lastSlashIndex+1), address.substring(lastSlashIndex + 1));

        } else {
            System.err.println("Could not figure out local file name for "
                    + address);
        }
    }

    public static void main(String[] args) {

        download("D://output.xml");
        /*
         * for (int i = 0; i < args.length; i++) { download(args[i]); }
         */
    }
}

我以这种格式得到了你的传递输入的 Ur Point

download("C:\\Documents and Settings\\ocp\\output.xml");

用('\')作为分隔符,所以会发生错误..解决这个问题..两个选项

1) 你必须在上面的程序中替换这一行

int lastSlashIndex = address.lastIndexOf('/');


int lastSlashIndex = address.lastIndexOf('\\');

2) 不要更改上述程序中的任何内容

使用 ('/') 作为分隔符传递这样的输入

download("C://Documents and Settings//ocp//output.xml");

它将成功运行..

使用这种类型的身份验证.... 下载 common-codec1.1.jar(from here) 并将其放在类路径中

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;



public class ConnectToUrlUsingBasicAuthentication {

    public static void main(String[] args) {

        try {
            String webPage = "http://google.com";
            String name = "youraddress@gmail.com";
            String password = "urpwd";

            String authString = name + ":" + password;
            System.out.println("auth string: " + authString);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            System.out.println("Base64 encoded auth string: " + authStringEnc);

            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

如果您遇到任何问题,请告诉我

【讨论】:

  • 嗨,我试过了,但无法找出“+ c:/users/praveen/praveen.xml”的本地文件名
  • 嗨,naren 似乎路径已解决。包含身份验证器类后,我得到 http 401 错误..试图检查出了什么问题
  • java.io.IOException:服务器返回 HTTP 响应代码:URL 的 401:在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon nection.java:1625) 处的 URL。 net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Http sURLConnectionImpl.java:254) 在 T_save.download(T_save.java:28) 在 T_save.download(T_save.java:98) 在 T_save.main(T_save.java: 108)跨度>
  • 运行程序后出现上述错误。我更新了我正在使用的问题中的代码
  • 正确检查您的用户名和密码...您的代码在哪里应用身份验证?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2021-09-29
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多