Android从服务器上下载文件

废话就不多说了直接看下怎么实现

1.添加相关的权限,设备API大于6.0时需要主动申请权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

//设备API大于6.0时,主动申请权限
    private void requestPermission(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 0);

            }
        }
    }

2.连接服务器获取文件

    /**
     * 从服务器下载文件
     * @param path 下载文件的地址
     * @param FileName 文件名字
     */
    public static void downLoad(final String path, final String FileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {
                            FileUtils fileUtils = new FileUtils();
                            fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));//指定文件保存路径,代码看下一步
                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

3.创建文件保存路径

public class FileUtils {
    private String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";

    public FileUtils() {
        File file = new File(path);
        /**
         *如果文件夹不存在就创建
         */
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 创建一个文件
     * @param FileName 文件名
     * @return
     */
    public File createFile(String FileName) {
        return new File(path, FileName);
    }
}

4.下载示例

downLoad("http://www.shidoe.com/shidoe/Edition/upfile/04.png", "che.png");//下载完成后就可以在手机目录里查看到了

5.动态获取需要保存文件的文件名

//获取 / 最后一次出现的位置,然后位置+1截取剩余的就是文件名了
String s = "http://www.shidoe.com/shidoe/Edition/upfile/04.png";
        int i = s.lastIndexOf("/");
        String FileName= s.substring(i + 1);

6.加载刚下载好的图片显示在界面上还是非常easy的

 private void loadImage() {
        String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";
        try {
            Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(new File(path, "che.png")));
            iv.setImageBitmap(bmp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

如果帮到了你就帮忙顶一下吧

要在Android应用程序中从SFTP服务器下载文件,您可以使用JSch库来实现。以下是一个简单的示例代码片段,演示了如何进行SFTP文件下载: ```java import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class SftpDownloader { private static final String HOST = "your_sftp_host"; private static final int PORT = 22; private static final String USERNAME = "your_sftp_username"; private static final String PASSWORD = "your_sftp_password"; private static final String REMOTE_FILE_PATH = "/path/to/remote/file"; private static final String LOCAL_FILE_PATH = "/path/to/local/file"; public static void downloadFile() { JSch ssh = new JSch(); Session session = null; try { session = ssh.getSession(USERNAME, HOST, PORT); session.setPassword(PASSWORD); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; InputStream inputStream = sftpChannel.get(REMOTE_FILE_PATH); OutputStream outputStream = new FileOutputStream(LOCAL_FILE_PATH); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); outputStream.close(); sftpChannel.disconnect(); channel.disconnect(); session.disconnect(); System.out.println("File downloaded successfully."); } catch (Exception e) { e.printStackTrace(); } } } ``` 请确保将`your_sftp_host`,`your_sftp_username`,`your_sftp_password`,`/path/to/remote/file`和`/path/to/local/file`替换为实际的SFTP服务器主机,用户名,密码以及远程和本地文件的路径。 以上代码将从SFTP服务器下载文件并保存在本地位置。您可以根据您的需求进行调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code-Porter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值