我正在一个非常旧的java应用程序中编写csv文件,因此我不能使用所有新的Java8流。
Writer writer = new OutputStreamWriter(new FileOutputStream("file.csv"));
writer.append("data,");
writer.append("data,");..。
然后,我需要将编写器对象转换为ByteArrayInputStream。我该怎么做呢?
提前谢谢。诚挚的问候。
发布于 2021-06-30 02:59:44
这取决于你想要做什么。
如果您正在向文件中写入大量数据,然后读取该文件,则需要使用FileInputStream来代替ByteArrayInputStream。
如果你想把一堆数据写到一个字节数组中,那么你应该考虑一下使用ByteArrayOutputStream。如果需要将字节数组作为ByteArrayInputStream读取,可以将ByteArrayOutputStream传递到输入流中,如下所示。请记住,这只适用于写作,然后阅读。您不能将其用作缓冲区。
//Create output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Create Writer
Writer writer = new OutputStreamWriter(out);
//Write stuff
...
//Close writer
writer.close();
//Create input stream using the byte array from out as input.
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());发布于 2021-06-30 02:48:17
简短的回答是:你不能。
ByteArrayInputStream不能从OutputStreamWriter中赋值。
因为您可能是在写,所以您可以将文件读回byte[],然后用它构造一个ByteArrayInputStream:
File file = new File("S:\\Test.java");
FileInputStream fis = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
fis.read(content,0,content.length);
ByteArrayInputStream bais = new ByteArrayInputStream(content);发布于 2021-06-30 02:55:31
您可以使用此代码。
class Sample implements Serializable {
public void display() {
System.out.println("sample class");
}
}
public class ObjectToByteArray {
public static void main(String args[]) throws Exception {
Sample obj = new Sample();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
byte [] data = bos.toByteArray();
}
}https://stackoverflow.com/questions/68183957
复制相似问题