如何在java中写二进制文件

时间:2015-06-30 05:12:17

标签: java

如何将最终文件设置为二进制文件,而不是ASCII文件,因此如果我在文本编辑器中打开file.bin,则无法读取它包含的内容。 以下类负责控制在文件中编写和读取arraylist。

代码:

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();
    }    
}

2 个答案:

答案 0 :(得分:2)

将二进制内容写入文件和使用二进制输出流写入内容(如文本)之间存在很大差异。

例如,如果你有一个像&#34; ABCDEF&#34;您可以使用FileWriter(文本输出流的示例)和FileOutputStream(二进制输出流的示例)将其写入文件。但这并不意味着如果打开该文件,您会看到不同的输出。

如果要使用二进制输出,则应将其转换为二进制值,然后写入文件。

还可以使用ObjectOutputStream将对象写入文件,使输出文件接近您想要的位置。

在您提供的代码段中,您可以将整个ArrayList对象写入文件。它使输出文件的可读性降低。

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

以及下次要阅读时:

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

希望这会有所帮助,

祝你好运。

答案 1 :(得分:0)

Rember this table(希望我没有忘记任何事情)

     |        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 |                     |
-------------------------------------------------