开发者

How can I write a sequence of strings and then a byte array to a file?

I want to write first a sequence of strings and then a sequence of bytes into a file, using Java. I started by using FileOutputStream because of the array of bytes. After searching the API, I realised that FileOutputStream cannot write Strings, only ints and bytes, so I switched to DataOutputStream. When I run the program, I get an exception. Why?

Here's a portion of my code:

 try {
            // Create the file
            FileOutputStream fos;
            DataOutputStream dos; // = new DataOutputStream("compressedfile.ecs_h");
            File file= new File("C:\\MyFile.txt");
            fos = new FileOutputStream(file);
            dos=new DataOutputStream(fos);

            /* saves the characters as a dictionary into the file before the binary seq*/
            for (int i = 0; i < al.size(); i++) {
                String name= al.get(i).name; //gets the string from a global arraylist, don't pay attention to this!
                dos.writeChars(name); //saving the name in the file
            }

            System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! ");

            dos.writeChars("><");
            String strseq;

            /*write all elements from the arraylist into a string variable*/
            strseq= seq.toString();开发者_JAVA技巧
            System.out.println("sTringSeq: " + strseq);

            /*transpose the sequence string into a byte array*/
            byte[] data = new byte[strseq.length() / 8];

            for (int i = 0; i < data.length; i++) {
                data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2);
                dos.write(data[i]);
            }


            dos.flush();
            //Close the output stream
            dos.close(); 
} catch(Exception e){}


The problem with your code is that the last for loop was counting over the wrong number of bytes. The code below fixes your problem writing your test data to a file. This works on my machine.

public static void main(String[] args) {

    ArrayList<String> al = new ArrayList<String>();
    al.add("String1");
    al.add("String2");

    try {
        // Create the file
        FileOutputStream fos = new FileOutputStream("MyFile.txt");
        DataOutputStream dos = new DataOutputStream(fos);

        /* saves the characters as a dictionary into the file before the binary seq */
        for (String str : al) {
            dos.writeChars(str);
        }

        System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! ");

        dos.writeChars("><");
        String strseq = "001100111100101000101010111010100100111000000000";

        // Ensure that you have a string of the correct size
        if (strseq.length() % 8 != 0) {
            throw new IllegalStateException(
                    "Input String is cannot be converted to bytes - wrong size: "
                            + strseq.length());
        }

        int numBytes = strseq.length() / 8;
        for (int i = 0; i < numBytes; i++) {
            int start = i * 8;
            int end = (i + 1) * 8;
            byte output = (byte) Integer.parseInt(strseq.substring(start, end), 2);
            dos.write(output);
        }

        dos.writeChars("> Enf of File");
        dos.flush();
        // Close the output stream
        dos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The approach of writing bytes directly to a test file does have a few problems (I assume that it's a text file in that your test file name ends with .txt), the most obvious one being that some text editors don't handle/display null characters very well (your last test byte was: 00000000 or null). If you want to see the bytes as readable bytes then you could investigate encoding them using Base64 encoding.


Line:

data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2);

looks very suspiciously...

can you provide move details about strseq and its value?


What about this code ?

this code :


        byte[] data = new byte[strseq.length() / 8];

        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2);
            dos.write(data[i]);
        }

becomes


        byte[] data = strseq.getBytes();


With the FileWriter class you have a nice abstraction of a file writing operation.

May this class can help you to write your file...

You can substitute the other OutputStreams by only this class. It have all the methods of you want for write a string and a byte array in a file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜