2

How can I make the final file to be in binary, but not in ASCII, so if I open the file.bin in a text editor, it not be able to read what it contains. The following class is responsable to control writing and reading the arraylist in the files.

Code:

package IOmanager;    
import data.ControlData;
import data.Sheet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author lcsvcn
 */
public class IO_Manager {
    private static final String src = "src/IOmanager/file.bin";
    private ArrayList<Sheet> al = null;
    private boolean hasArray;
    private ControlData cd;
    public IO_Manager(ControlData cd) {
        this.cd = cd;
        loadArray();
    }

    private void saveArray() {

        if(al.isEmpty()) {        
            System.out.println("ArrayList is empty");
        } else if(al == null) {
            System.out.println("ArrayList is null send some array");    
        } else {
            File fout = new File(src);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(fout);
            } catch (FileNotFoundException ex) {
                System.out.println("FileNotFoundException");
                Logger.getLogger(IO_Manager.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {


try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(src, true)))) {
//                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
//                try {
                        for(Sheet s : al) { 

                            // Cod Ficha
                            System.out.println("w: "+ s.getSheetID()); 

                            out.println(Integer.toString(s.getSheetID()));
//                            bw.newLine();

                            // Nome 
                            System.out.println("w: " + s.getName());  

                            out.println(s.getName());
//                            bw.newLine();

                            // Idade
                            System.out.println("w: " + s.getAge());  

                            out.println(Integer.toString(s.getAge()));
//                            bw.newLine();
                            // Plano de Saude
                            System.out.println("w: "+ s.getHealthyCarePlan());  

                            out.println(Integer.toString(s.getHealthyCarePlan()));
//                            bw.newLine();

                            // Estado Civil
                            System.out.println("w: "+ s.getMaritalStatus());  

                            out.println(Integer.toString(s.getMaritalStatus()));

//                            bw.newLine();

                        }

                out.close();
                } catch (IOException ex) {
                        System.out.println("IOException");
                        Logger.getLogger(IO_Manager.class.getName()).log(Level.SEVERE, null, ex);
                }

                System.out.println("saved");
            } catch (NullPointerException e) {
                System.out.println("fucked");
            }
        }
    }
    private boolean loadArray() {
        File fin = new File(src);
        FileInputStream fis = null;
        String name="erro";
        int age=-1; 
        int sId=-1;
        int hCarePlan=-1;
        int mStatus=-1;

        int cont = 0;
        int num = 5;
        int reg = 0;

        try {
            fis = new FileInputStream(fin);
        } catch (FileNotFoundException ex) {
            System.out.println("File to load not found!");
            return false;
        }

        //Construct BufferedReader from InputStreamReader
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

                System.out.println("-------------");
                System.out.println("inicio da leitura");
                System.out.println("-------------");

            String line = null;
            try {
                 System.out.println("Reg num: " + reg);

                while((line = br.readLine()) != null) {
                    switch(cont) {
                        case 0:
                            sId = Integer.valueOf(line);
                            System.out.println("r: " + sId);
                            break;
                        case 1:
                            name = line;
                            System.out.println("r: " + name);
                            break;
                        case 2:
                            age = Integer.valueOf(line);
                            System.out.println("r: " + age);
                            break;
                        case 3:
                            hCarePlan = Integer.valueOf(line);
                            System.out.println("r: " + hCarePlan);
                            break;
                        case 4:
                            mStatus = Integer.valueOf(line);
                            System.out.println("r: " + mStatus);  
                            break;
                    }
                    // Fim de um registro e comeco de outro
                    if(cont >= num) {
                        cd.sendData(name, age, mStatus, hCarePlan, sId);
                        cont = 0;
                        reg++;
                        System.out.println("-------------");
                        System.out.println("Reg num: " + reg);
                    }
                    cont++;
                }   
                br.close();
                System.out.println("-------------");
                System.out.println("fim da leitura");
                System.out.println("-------------");
            } catch (IOException ex) {
                Logger.getLogger(IO_Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("load");
            return true;

    }

    public void setArray(ArrayList<Sheet> mList) {
        al = mList;
        saveArray();
    }    
}
4
  • 3
    Maybe you should clarify to yourself what "binary" means. A text file is just a binary file where all the characters are human readable. Commented Jun 30, 2015 at 5:20
  • 1
    Are you asking about encryption? Commented Jun 30, 2015 at 5:38
  • 1
    FileWriters are for text. You should be using FileOutputStream, for a start. Commented Jun 30, 2015 at 5:40
  • can you please post only the relevant section of your code? Commented Jun 30, 2015 at 6:06

2 Answers 2

2

There are a big difference between writing binary contents into a file and writing contents(such as texts) using binary output streams.

For example if you have a String like "ABCDEF" you can write it to a file using both FileWriter(example of a text output stream) and FileOutputStream(example of a binary output stream). But this not means if you open that file you see different outputs.

If you want to have binary outputs you should convert it to binary values and then write to the file.

Also have an alternative to use ObjectOutputStream to write objects into a file which makes the output file something near what you want.

In the snippet code you provided you can write the whole ArrayList object into the file. It makes the output file less human readable.

ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(al);

and the next time when you want to read it:

ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(src)));
ArrayList<Sheet> allSheets = (ArrayList<Sheet>)in.readObject();

Hope this would be helpful,

Good Luck.

Sign up to request clarification or add additional context in comments.

1 Comment

It's partially worked for me. The reading part is getting IOException at line 'ArrayList<Sheet> allSheets = (ArrayList<Sheet>)in.readObject();' and I'm not been able to load the file correctly.
2

Rember this table (hope i didn't forget anything)

     |        Input       |       Output        |
------------------------------------------------|
     |BufferedReader      |BufferedWriter       |
     |CharArrayReader     |CharArrayWriter      |
     |FileReader          |FileWriter           |
Char |InputStreamReader   |OutputStreamWriter   |
     |LineNumberReader    |                     |
     |PipedReader         |PipedWriter          |
     |PushbackReader      |                     |
     |StringReader        |StringWriter         |
     |                    |PrintWriter          |
------------------------------------------------|
     |BufferedInputStream |BufferedOutputStream |
     |ByteArrayInputStream|ByteArrayOutputStream|
     |DataInputStream     |DataOuputStream      |
     |FileInputStream     |FileOutputStream     |
Bin  |ObjectInputStream   |ObjetOutputStream    |
     |PipedInputStream    |PipedOutputStream    |
     |                    |PrintStream          |
     |PushbackInputStream |                     |
     |SequenceInputStream |                     |
-------------------------------------------------

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.