开发者

Android write to file

开发者 https://www.devze.com 2023-04-04 09:35 出处:网络
I\'ve made I simple function to write from URL to file. Everything works good until out.write(), I mean there\'s no exception, but it just doesn\'t write anything to file

I've made I simple function to write from URL to file. Everything works good until out.write(), I mean there's no exception, but it just doesn't write anything to file

Here's code

private boolean getText(String url, String name) throws IOException {
    if(url!=null){
        FileWriter fstream = new FileWriter(PATH+"/"+name+".txt");
        BufferedWriter out = new BufferedWriter(fstream);
        URL _url =  new URL(url);
        int code = ((HttpURLConnection) _url.openConnection()).getResponseCode();
        if(code==200){
            URLConnection urlConnection = _url.openConnection(); //
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) != -1) {
                    String chunk = new String(buffer, 0, 开发者_Python百科bytesRead);
                    out.write(chunk);
            }

            return true;
        }
        out.close();

    }
    return false;
}

Can someone tell me what's wrong please?


Try fstream.flush().

Also out.close() should be called before returning from a function.

0

精彩评论

暂无评论...
验证码 换一张
取 消