Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java urlconnection返回的文本文件出错_Java_Android_File_Url - Fatal编程技术网

Java urlconnection返回的文本文件出错

Java urlconnection返回的文本文件出错,java,android,file,url,Java,Android,File,Url,我是android新手,所以需要一些帮助。我正在编写一个简单的测试,用于我的android应用程序。 代码尝试从url获取文本文件并存储在SD卡中 在asyntask中,代码为: try { URL url = new URL("https://sites.google.com/site/ghadeerdarwesh93/downl/gh.txt" ); HttpURLConnection urlConnection = (HttpURLConnection) u

我是android新手,所以需要一些帮助。我正在编写一个简单的测试,用于我的android应用程序。 代码尝试从url获取文本文件并存储在SD卡中

在asyntask中,代码为:

try {
        URL url = new URL("https://sites.google.com/site/ghadeerdarwesh93/downl/gh.txt" );
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
       urlConnection.setRequestProperty("Accept-Encoding", "identity");
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        int  totalSize = urlConnection.getContentLength();
       Log.i("totalSize","totalSize=" + Integer.toString(totalSize));

        //set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, to save the downloaded file
        File file = new File(SDCardRoot,"gh.txt");

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        BufferedInputStream inputStream = new BufferedInputStream(url.openStream());

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength ;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when complete //
        fileOutput.close();
    }
当它完成时,我在SD卡中找到了gh.txt,但它是(1kb),并且有未知数据。 很快它就是一个错误的文件

我在清单中正确添加了权限

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


实际问题是什么?文件太短,还是完全错误?在
文件输出之前添加一个
Log
调用。写入
,以便查看您(试图)写入的字节数。您必须调用fileOutput.flush()在关闭itThanks alot.total size return-1之前,我想是因为响应主体。actul文件只包含我的名字,但我发现了以下几行和更多内容:HTTP/1.1 302临时移动内容类型:text/html;字符集=UTF-8位置: