java 在Java中,如何仅在内存中创建一个临时文件来解析xml?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5095896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, how do I create a temp file only in memory to parse xml?
提问by bmw0128
I'd like to read in an XML response and make a temp file in memory out of the xml. Then, I'd like to read in the file to see if certain elements exist. After this is done, I'd like to just get rid of the temp file. I am familiar with making and reading files to/from the file system, is it possible to not write, and then read, from a file in memory only?
我想读入一个 XML 响应并在内存中从 xml 中创建一个临时文件。然后,我想读入文件以查看是否存在某些元素。完成此操作后,我想删除临时文件。我熟悉在文件系统中创建文件和从文件系统读取文件,是否可以不写入,然后仅从内存中的文件读取?
采纳答案by Jon Skeet
Why would you bother creating it as a "file" in memory? Just keep it as an XML representation (whether that's using JDOM, the W3C DOM API or whatever).
你为什么要把它创建为内存中的“文件”?只需将其保留为 XML 表示(无论是使用 JDOM、W3C DOM API 还是其他)。
It will be a lot simpler to examine in thatformat than as a "file" in memory. After all, if you had the serialized form of it, as it would appear on disk, then in order to query it you'd basically have to parse it again anyway!
以这种格式检查比作为内存中的“文件”要简单得多。毕竟,如果你有它的序列化形式,就像它出现在磁盘上一样,那么为了查询它,你基本上必须再次解析它!
回答by Mark Peters
Does it really need to be a file? Typically that is abstacted away.
它真的需要是一个文件吗?通常,这是抽象的。
For example, if you are using a stream-based writer or reader, you can use ByteArrayOutputStream
and ByteArrayInputStream
and wrap your streams/writers/readers around that. It would be very seldom that you should need to mock a file itself; if you do you're probably not abstacting as much as you could in your design.
例如,如果您使用的是基于流的写入器或读取器,则可以使用ByteArrayOutputStream
并ByteArrayInputStream
围绕它包装您的流/写入器/读取器。您很少需要模拟文件本身;如果你这样做了,你可能不会在你的设计中尽可能多地进行抽象。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(baos);
w.write(...);
byte[] bytes = baos.toByteArray();
Similarly, a ByteBuffer
can wrap a File but also simply an array of bytes in memory.
类似地, aByteBuffer
可以包装 File ,但也可以包装内存中的一个字节数组。
It seems like you don't even need it serialized at all however, as Jon notes.
然而,正如 Jon 所指出的,您似乎根本不需要序列化它。
回答by limc
I don't see a need for you to create a temp file just to check the certain elements exist. Most XML parsers allow you to read directly from some input stream. All you need is to convert your XML response string into an input stream, then feed it to some XML parser to perform your check:-
我认为您不需要创建临时文件来检查某些元素是否存在。大多数 XML 解析器允许您直接从某些输入流中读取。您所需要的只是将您的 XML 响应字符串转换为输入流,然后将其提供给某个 XML 解析器以执行您的检查:-
// converting string to input stream
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );