Java中的DataOutStream类

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

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语句来自动关闭资源。

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Class to demonstrate usage of DataOutputStream class.
* @author javaguides.net
*
*/
public class DataOutputStreamExample {
 private static final Logger LOGGER = LoggerFactory.getLogger(DataOutputStreamExample.class);

 public static void main(String[] args) {

  final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
  final int[] units = { 12, 8, 13, 29, 50 };
  final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

  try (DataOutputStream out = new DataOutputStream(
    new BufferedOutputStream(new FileOutputStream("sample.txt")))) {
   for (int i = 0; i < prices.length; i++) {
    out.writeDouble(prices[i]);
    out.writeInt(units[i]);
    out.writeUTF(descs[i]);
   }
  } catch (IOException e) {
   LOGGER.error(e.getMessage());
  }
 }
}

相关文章

微信公众号

最新文章

更多