66

我正在从 url 检索 XML 提要,然后对其进行解析。我需要做的是将其存储在手机内部,这样当没有互联网连接时,它可以解析保存的选项而不是实时选项。

我面临的问题是我可以创建 url 对象,使用 getInputStream 获取内容,但它不会让我保存它。

URL url = null;
InputStream inputStreamReader = null;
XmlPullParser xpp = null;

url = new URL("http://*********");
inputStreamReader = getInputStream(url);

ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFileAppeal.srl"));

//--------------------------------------------------------
//This line is where it is erroring.
//--------------------------------------------------------
out.writeObject( inputStreamReader );
//--------------------------------------------------------
out.close();

有什么想法可以保存输入流,以便以后加载。

干杯

4

8 回答 8

117

在这里,输入是你的inputStream. 然后使用相同的文件(名称)并FileInputStream在将来读取数据。

try {
    File file = new File(getCacheDir(), "cacheFileAppeal.srl");
    try (OutputStream output = new FileOutputStream(file)) {
        byte[] buffer = new byte[4 * 1024]; // or other buffer size
        int read;

        while ((read = input.read(buffer)) != -1) {
            output.write(buffer, 0, read);
        }

        output.flush();
    }
} finally {
    input.close();
}
于 2012-06-01T21:12:03.017 回答
35

Simple Function

Try this simple function to neatly wrap it up in:

// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
    OutputStream out = null;

    try {
        out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
    } 
    catch (Exception e) {
        e.printStackTrace();
    } 
    finally {
        // Ensure that the InputStreams are closed even if there's an exception.
        try {
            if ( out != null ) {
                out.close();
            }

            // If you want to close the "in" InputStream yourself then remove this
            // from here but ensure that you close it yourself eventually.
            in.close();  
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}

Thanks to Jordan LaPrise and his answer.

于 2015-01-24T23:15:18.260 回答
24

Kotlin版本(经过测试,无需库):

fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
    inputStream.use { input ->
        val outputStream = FileOutputStream(outputFile)
        outputStream.use { output ->
            val buffer = ByteArray(4 * 1024) // buffer size
            while (true) {
                val byteCount = input.read(buffer)
                if (byteCount < 0) break
                output.write(buffer, 0, byteCount)
            }
            output.flush()
        }
    }
}

我们利用了use最后会自动关闭两个流的功能。

即使发生异常,流也会正确关闭。

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html
https://kotlinlang.org/docs/tutorials/kotlin-for-py/scoped-resource-usage.html

于 2019-05-10T08:57:18.127 回答
7

一个较短的版本:

OutputStream out = new FileOutputStream(file);
fos.write(IOUtils.read(in));
out.close();
in.close();
于 2016-10-10T10:28:43.730 回答
7

这是一个处理所有异常并基于先前答案的解决方案:

void writeStreamToFile(InputStream input, File file) {
    try {
        try (OutputStream output = new FileOutputStream(file)) {
            byte[] buffer = new byte[4 * 1024]; // or other buffer size
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
于 2017-12-19T16:45:21.247 回答
3
  1. 在您的应用程序build.gradle文件中添加dependencies
    implementation 'commons-io:commons-io:2.5'
  1. 在您的代码中:
import org.apache.commons.io.FileUtils;

// given you have a stream, e.g.
InputStream inputStream = getContext().getContentResolver().openInputStream(uri);

// you can now write it to a file with
FileUtils.copyToFile(inputStream, new File("myfile.txt"));

于 2020-03-08T15:34:37.133 回答
1

有IOUtils的方式:

copy(InputStream input, OutputStream output)

它的代码与此类似:

public static long copyStream(InputStream input, OutputStream output) throws IOException {
    long count = 0L;
    byte[] buffer = new byte[4096]; 
    for (int n; -1 != (n = input.read(buffer)); count += (long) n)
        output.write(buffer, 0, n);
    return count;
}
于 2017-12-09T17:37:49.803 回答
0

你可以使用谷歌番石榴

 import com.google.common.io.ByteStreams;

代码:

 try (FileOutputStream fos = new FileOutputStream(new File("C:\\example.txt"))){
      ByteStreams.copy(inputStream, fos)
 }
于 2021-11-29T06:31:36.913 回答