Java中的DataOutStream类

x33g5p2x  于2022-10-06 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(1211)

Java DataOutputStreamclass允许应用程序以独立于机器的方式向输出流写入原始的Java数据类型。

Java应用程序通常使用数据输出流来写数据,这些数据以后可以由数据输入流读取。

DataOutputStream类 构造函数

DataOutputStream(OutputStream out) - 创建一个新的数据输出流,将数据写入指定的基础输出流。

DataOutputStream类方法

void flush() - 冲洗这个数据输出流。
int size() - 返回写的计数器的当前值,到目前为止写到这个数据输出流的字节数。
void write(byte[] b, int off, int len) - 从偏移量off开始,将指定字节数组中的len字节写入底层输出流。
void write(int b) - 将指定的字节(参数b的低八位)写到底层输出流中。
void writeBoolean(boolean v) - 将一个布尔值作为一个字节值写入底层输出流。
void writeByte(int v) - 将一个字节写到底层输出流中,作为一个1字节的值。
void writeBytes(String s) - 将字符串作为一个字节序列写到底层输出流中。
void writeChar(int v) - 将一个char作为2字节的值写到底层输出流中,高字节在前。
void writeChars(String s) - 将一个字符串作为一个字符序列写入底层输出流。
void writeDouble(double v) - 使用Double类中的doubleToLongBits方法将double参数转换为long,然后将该long值作为一个8字节的量写入底层输出流,高字节优先。
void writeFloat(float v) - 使用Float类中的floatToIntBits方法将float参数转换为int,然后将int值作为一个4字节的数量写入底层输出流,高字节在前。
void writeInt(int v) - 将一个int值作为4个字节写到底层输出流中,高字节在前。
void writeLong(long v) - 将一个long写入底层输出流,作为8个字节,高字节在前。
void writeShort(int v) - 将一个短字节写到底层输出流中,作为两个字节,高字节在前。
void writeUTF(String str) - 使用修改过的UTF-8编码,以独立于机器的方式将一个字符串写入底层输出流。

DataOutStream类实例

这个例子使用try-with-resources语句来自动关闭资源。

  1. import java.io.BufferedOutputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. /**
  8. * Class to demonstrate usage of DataOutputStream class.
  9. * @author javaguides.net
  10. *
  11. */
  12. public class DataOutputStreamExample {
  13. private static final Logger LOGGER = LoggerFactory.getLogger(DataOutputStreamExample.class);
  14. public static void main(String[] args) {
  15. final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
  16. final int[] units = { 12, 8, 13, 29, 50 };
  17. final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
  18. try (DataOutputStream out = new DataOutputStream(
  19. new BufferedOutputStream(new FileOutputStream("sample.txt")))) {
  20. for (int i = 0; i < prices.length; i++) {
  21. out.writeDouble(prices[i]);
  22. out.writeInt(units[i]);
  23. out.writeUTF(descs[i]);
  24. }
  25. } catch (IOException e) {
  26. LOGGER.error(e.getMessage());
  27. }
  28. }
  29. }

相关文章

最新文章

更多