首页 > 解决方案 > 如何下载私人文件夹中的文本文件并在文本视图中显示文本文件内容

问题描述

我想从服务器的私人文件夹中下载文本文件,用户应该无法访问。简而言之,我只想将该文件存储在应用程序文件夹中,而不是存储卡/内存中。下载完成后,我想在文本视图中显示文本文件。如果文件已下载或存在于文件夹中,则只想显示该文件内容。有人能帮助我吗?提前致谢。

这是代码 -

            url = new URL("https://tmpfiles.org/dl/11433/baby_shark_dodo.txt");
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            connection.setRequestMethod("GET");

            try {
                File mydir = getApplicationContext().getDir("Songs", Context.MODE_PRIVATE);
                if(!mydir.exists()){
                    mydir.mkdir();
                }
                final File file = new File(mydir,"Test.txt");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int bufferLength = 0;

                while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    fileOutputStream.write(buffer, 0, bufferLength);
                }
                fileOutputStream.close();
                connection.disconnect();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

标签: androidtextviewtext-filesandroid-download-manager

解决方案


推荐阅读