例子
以下示例显示java.io.DataOutputStream.writeBytes(String s)方法的用法。
package com.jc2182;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class DataOutputStreamDemo {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
String s = "Hello World!!";
try {
// create byte array output stream
baos = new ByteArrayOutputStream();
// create data output stream
dos = new DataOutputStream(baos);
// write to the output stream from the string
dos.writeBytes(s);
// flushes bytes to underlying output stream
dos.flush();
System.out.println(s+" in bytes:");
// for each byte in the buffer content
for(byte b:baos.toByteArray()) {
// print byte
System.out.print(b + ",");
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
} finally {
// releases all system resources from the streams
if(baos!=null)
baos.close();
if(dos!=null)
dos.close();
}
}
}
让我们编译并运行以上程序,这将产生以下结果-
Hello World!! in bytes:
72,101,108,108,111,32,87,111,114,108,100,33,33,