How to write and read short array from file using DataOutputStream() and DataInputStream() in Java

1 Answer

0 votes
package javaapplication1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        String sFilePath = "d://data.txt";
        short[] sArr = {100, 3000, 9989, 9900, 9874, 8987};

        try {

            DataOutputStream dos;
            try (FileOutputStream fos = new FileOutputStream(sFilePath)) {
                dos = new DataOutputStream(fos);
                for (short s : sArr) {
                    dos.writeShort(s);
                }
            }

            DataInputStream dis;
            try (InputStream is = new FileInputStream(sFilePath)) {
                dis = new DataInputStream(is);
                while (dis.available() > 0) {
                    short s = dis.readShort();
                    System.out.print(s + " ");
                }
            }

        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }
}

/*
      
run:

100 3000 9989 9900 9874 8987
  
 */

 



answered Nov 11, 2016 by avibootz
...