当前位置: 代码迷 >> J2SE >> !怎么输出SHORT数组到文件
  详细解决方案

!怎么输出SHORT数组到文件

热度:90   发布时间:2016-04-24 12:41:20.0
十万火急!!如何输出SHORT数组到文件
内存中有一个SHORT数组,如何输出到文件,采用二进制格式把内存中数据原封不动输出文件~麻烦大家帮帮忙!~

------解决方案--------------------
[code=Java][/code] public static final byte[] toByteArray(short changeData)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
byte[] setByteData = null;

try 
{
dos.writeShort(changeData);
setByteData = baos.toByteArray();

catch (Exception e) 
{
printStackTrace(e);
}
return setByteData;
}
------解决方案--------------------
Java code
import java.io.File;import java.io.FileOutputStream;import java.io.IOException; public class WriteShorts {     public static void main(String[] args) throws Exception {        short[] shorts = {1, 2, 3, 4, 5};        String filename = "c:\\data.dat";        writeShorts(shorts, filename);    }     private static void writeShorts(short[] shorts, String filename) throws IOException {        File file = createFile(filename);        FileOutputStream fos = new FileOutputStream(file);        for (short aShort : shorts) {            fos.write(toBytes(aShort));        }        fos.close();    }     private static File createFile(String filename) throws IOException {        File file = new File(filename);        if (!file.exists()) {            file.createNewFile();        }        return file;    }     private static byte[] toBytes(short aShort) {        return new byte[]{                (byte) ((aShort >> 8) & 0xFF),                 (byte) (aShort & 0xFF)        };    }}
------解决方案--------------------
探讨
Java codeimportjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;publicclassWriteShorts {publicstaticvoidmain(String[] args)throwsException {short[] shorts={1,2,3,4,5};
String filename="c:\\data.dat";
writeShorts(shorts, filename);
}privatestaticvoidwriteShorts(short[] shorts, String filename)throwsIOException {
File file=createFile(filename);

  相关解决方案