请问java如何读写二进制文件?
如:一个文件8个字节,
前四个字节为(long)销售额,
后面四个字节(long)为入库金额,
C只要几个read和write就能搞定,
java该怎么做啊?
如果我要读前四他字节并显示代码该怎么写?

解决方案 »

  1.   

    可以用DataInputStream和DataOutputStream这两个类来写二进制文件
      

  2.   

    File f=new File(sfileName);
        try{
            FileInputStream fs = new FileInputStream(f);
            DataInputStream rd=new DataInputStream(fs); 
            try{
              x=rd.readLong(); 
            }
            catch(IOException e){
              pmsg("Read total file error: "+e.getMessage(),true);
            }
    结果不对,我只要前四个字节的内容
      

  3.   

    UP... int read(byte[] b)
      

  4.   

    我的代码有什么问题吗?
        File f=new File(sfileName);
        //byte[] xs=new byte[4];
        try{
            FileInputStream fs = new FileInputStream(f);
            //BufferedInputStream rf= new BufferedInputStream(fs);
            DataInputStream rd=new DataInputStream(fs); 
            try{
              x=rd.readInt();
              t=rd.readInt();
              r=rd.readInt();
              q=rd.readInt();
            }
            catch(IOException e){
              pmsg("Read total file error: "+e.getMessage(),true);
            }
            pmsg("销售额: "+x,true);
            pmsg("退票额: "+t,true);
            pmsg("入库金额: "+r,true);
            pmsg("其他金额: "+q,true);
            try{
              rd.close();
              fs.close();
            }
            catch(IOException e){
              pmsg("close total file error:"+e.getMessage(),true);
            }
      

  5.   


    import java.io.*;
    import java.util.*;
    import java.util.zip.*;/**
     *
     * <p>Title: zip文件工具类,压缩和解压缩</p>
     * <p>Description:使用类的组合而非继承关系
     *                不做异常处理
     * </p>
     * <p>Copyright: Copyright (c) 2004</p>
     */
    public class ZipTool
    {    public static void extractFile(InputStream in, String path,
                                       boolean overWrite) throws IOException
        {        ZipInputStream zisTemp = null;        try
            {
                zisTemp = new ZipInputStream(new BufferedInputStream(in));
                ZipEntry e;            UnZIP zip = new UnZIP(zisTemp, path, overWrite);
                while ( (e = zisTemp.getNextEntry()) != null)
                {
                    zip.extractFile(e);
                }
            }
            catch (IOException ex)
            {            ex.printStackTrace();
                throw ex;
            }
            finally
            {
                zisTemp.close();
            }    }    public static void extractFile(InputStream in, String path) throws
            IOException
        {        extractFile(in, path, true);    }    public static void extractFile(String zipFile, String path,
                                       boolean overwrite) throws
            IOException
        {
                if (overwrite)
                {
                    extractFile(zipFile, path);
                }
                else
                {
                   InputStream in = new FileInputStream(zipFile);
                    extractFile(in, path, false);
                    in.close();
                }
            }
        public static void extractFile(String zipFile, String path) throws
            IOException
        {        FileInputStream fin = null;
            try
            {
                fin = new FileInputStream(zipFile);
                extractFile(fin, path);
            }
            catch (IOException ex)
            {            ex.printStackTrace();
                throw ex;
            }        finally
            {
                if (fin != null)
                {
                    fin.close();
                }
            }    }    /**
         * 把多文件或目录压缩成一个ZIP文件
         * @param ZIPfileName  目标zip文件名(全路径)
         * @param fileNames 源文件或目录名列表
         * @throws IOException
         */    /* For example
         ArrayList fileList = new ArrayList();
            fileList.add("c:\\hh\\tt.txt");
            fileList.add("c:\\hh\\tt1.txt");
            fileList.add("c:\\hh\\tt2.txt");
            //目录
            fileList.add("c:\\hh\\yy");
            ZipTool.ZipFile("c:\\temp.zip", fileList);
            ZipTool.extractFile("c:\\temp.zip", "c:\\hh1");
         */
        public static void ZipFile(String ZIPfileName, List fileNames) throws
            IOException
        {        if (fileNames == null || fileNames.size() == 0)
            {            throw new IllegalArgumentException("param fileNames is null!");        }        File[] files = new File[fileNames.size()];
            for (int i = 0; i < fileNames.size(); i++)
            {
                files[i] = new File( (String) fileNames.get(i));
            }
            ZipFile(ZIPfileName, files);    }    public static void ZipFile(String ZIPfileName, File[] files) throws
            IOException
        {        if (files == null || files.length == 0)
            {            throw new IllegalArgumentException("param fileNames is null!");        }
            ZipOutputStream zout = null;        try
            {
                zout = new ZipOutputStream(new FileOutputStream(new File(
                    ZIPfileName)));            for (int i = 0; i < files.length; i++)
                {
                    String filePath = (String) files[i].getAbsolutePath();
                    String rootPath = getParentPath(filePath);
                    ZIP ziptool = new ZIP(zout, rootPath);
                    ziptool.ZipFile(filePath);
                }
            }
            catch (IOException ex)
            {            ex.printStackTrace();
                throw ex;
            }        finally
            {
                if (null != zout)
                {
                    zout.closeEntry();
                    zout.close();
                }        }    }    /**
         * 压缩一个文件或文件夹到ZIP文件
         * @param ZIPfileName
         * @param filePath
         * @throws IOException
         */
        public static void ZipFile(String ZIPfileName, String filePath) throws
            IOException
        {        FileOutputStream fout = null;
            try
            {
                fout = new FileOutputStream(ZIPfileName);
                ZipFile(fout, filePath);
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
                throw ex;
            }
            finally
            {
                if (fout != null)
                {
                    fout.close();
                }
            }
        }    /**
         * 压缩一个文件或文件夹到一个字节数组
         * @param filePath
         * @return
         * @throws IOException
         */
        public static void ZipFile(OutputStream out, String filePath) throws
            IOException
        {        ZipOutputStream zout = null;
            try
            {            zout = new ZipOutputStream(new BufferedOutputStream(out));
                String rootPath = getParentPath(filePath);            new ZIP(zout, rootPath).ZipFile(filePath);        }
            catch (IOException ex)
            {
                ex.printStackTrace();
                throw ex;
            }        finally
            {
                if (null != zout)
                {
                    zout.closeEntry();
                    zout.close();
                }        }    }
      

  6.   

        /**
         * 返回文件上级的目录名称
         * @param absoluteFile
         * @return
         */
        private static String getParentPath(String fileName)
        {        File tempFile = new File(fileName);
            File parentFile = new File(tempFile.getAbsolutePath()).getParentFile();
            return parentFile.getAbsolutePath();
        }}class ZIP
    {    ZIP(ZipOutputStream zout, String rootPath)
        {        this.zout = zout;
            this.rootPath = rootPath;    }    private ZipOutputStream zout = null;
        private String rootPath = "/";    /**
         * 递规实现压缩文件
         * @param filePath
         * @throws IOException
         */
        protected void ZipFile(String filePath) throws IOException
        {
           if(filePath.indexOf("\\")!=-1)
        {
             filePath=filePath.replaceAll("\\\\","\\/");
          }        File f = new File(filePath);        String absolutePath = f.getAbsolutePath();
            f = new File(absolutePath);
            String entryName = absolutePath.substring(absolutePath.indexOf(rootPath) +
                                                      rootPath.length());
            if (f.isDirectory())
            {            ZipEntry ze = new ZipEntry(entryName + "/");
                zout.putNextEntry(ze);            File[] fileList = f.listFiles();
                for (int i = 0; i < fileList.length; i++)
                {
                    File subP = fileList[i];
                    ZipFile(subP.getAbsolutePath());
                }
            }
            else
            {
                if(entryName.indexOf("\\")!=-1)
                {
                    entryName=entryName.replaceAll("\\\\","\\/");
                }            writeEntry(entryName, f);
            }    }    /**
         * 写文件到ZIP
         * @param entryName
         * @param in
         * @throws IOException
         */
        protected void writeEntry(String entryName, File f) throws IOException
        {        ZipEntry ze = new ZipEntry(entryName);
            zout.putNextEntry(ze);
            DataInputStream din = new DataInputStream(new BufferedInputStream(new
                FileInputStream(f)));        //经典中的经典
            byte[] b= new byte[1024];
            int len = 0;
            while ( (len = din.read(b)) != -1)
            {
                zout.write(b, 0, len);
            }
            din.close();    }}class UnZIP
    {    UnZIP(ZipInputStream zin, String rootPath, boolean overwrite)
        {       this.zin = zin;
            this.rootPath = rootPath;
            this.overwrite = overwrite;    }    private ZipInputStream zin = null;
        private String rootPath = "/";
        private boolean overwrite = true;    /**
         *
         * @param e
         * @throws IOException
         */
        protected void extractFile(ZipEntry e) throws IOException
        {        String name = e.getName();
            if(name!=null&&name.startsWith("\\")){
              name = name.substring(1,name.length());
            }
            if(name.indexOf("\\")!=-1)
            {
                name=name.replaceAll("\\\\","\\/");        }        File f = new File(rootPath +"/"+ name);        if (e.isDirectory())
            {
                if (!f.exists() && !f.mkdirs() || !f.isDirectory())
                {
                    throw new IOException(new StringBuffer().append("创建目录").append(
                        e.getName()).append("失败").toString());
                }
            }
            else
            {            //如果文件存在,而且不允许覆盖返回不处理
                if (f.exists() && !overwrite)
                {                return;
                }
                if (f.getParent() != null)
                {
                    File d = new File(f.getParent());
                    if (!d.exists() && !d.mkdirs() || !d.isDirectory())
                    {
                        throw new IOException(new StringBuffer().append("创建文件").
                                              append(f.getName()).append("的父目录时失败").
                                              toString());
                    }
                }
                OutputStream os = new FileOutputStream(f);
                byte[] b = new byte[1024];
                int len;
                while ( (len = zin.read(b)) != -1)
                {
                    os.write(b, 0, len);
                }
                zin.closeEntry();
                os.close();
            }
        }
        /**
         * 删除文件
         * @param absoluteName
         * @return
         * @throws IOException
         */
        public String deleteTree(String absoluteName) throws IOException
        {
            String flag = "failure";
            File dir = new File(absoluteName);        //如果不存在
            if (!dir.exists())
            {
                flag = "noexist";
            }
            //如果不是目录
            else if (!dir.isDirectory())
            {            if (dir.delete())
                {
                    flag = "success";
                }        }
            else
            {            //是目录
                File[] entries = dir.listFiles();
                int sz = entries.length;
                for (int i = 0; i < sz; i++)
                {
                    if (entries[i].isDirectory())
                    {
                        deleteTree(entries[i].getAbsolutePath());
                    }
                    else
                    {
                        entries[i].delete();
                    }
                }
                if (dir.delete())
                {
                    flag = "success";
                }
            }
            return flag;
        }}
      

  7.   

    /**
         * 一对多文件传输
         * @param temZip
         * @param pathName
         * @throws RemoteException
         * @throws IOException
         */
        public ArrayList transferFile_M(ArrayList to, ArrayList files, String path) throws
            IOException, CustomAccessException
        {
            AuthorizationHelper.checkValidity();        //传输结果
            ArrayList result = new ArrayList();        long now = System.currentTimeMillis();
            //临时文件
            String localZip = TEMP_PATH + now + "local.tmp";
            String remoteZip = TEMP_PATH + now + "remote.tmp";
            DataInputStream din = null;        try
            {
                //压缩文件到临时文件
                zip(localZip, files);            //要传的机器数
                int j = to.size();
                for (int i = 0; i < j; i++)
                {
                    try
                    {
                        boolean overwrite;
                        String ss = (String) to.get(i);
                        if (ss.endsWith("y"))
                        {
                            overwrite = true;
                        }
                        else
                        {
                            overwrite = false;
                        }
                        String css = ss.substring(0, ss.length() - 1);
                        //绑定远程对象
                        FileTransfer fter = (FileTransfer) Naming.lookup("rmi://" +
                            css + "/" + REBIND_NAME);
                        if(!fter.isHaveDriver(path))
                        {
                            throw new Exception("not contain");
                        }
                        din = new DataInputStream(new
                                                  BufferedInputStream(new
                            FileInputStream(localZip)));
                        fter.startMonitor(remoteZip);
                        int len = 0;
                        byte[] b = new byte[1024 * 1024];
                        //在本地读,往远程写                    while ( (len = (din.read(b))) >= 0)
                        {                        fter.write(remoteZip, b, len);                    }
                        din.close();
                        //远程文件解压
                        fter.unZip(remoteZip, path, overwrite);
                        //删除远程文件
                        fter.remove(remoteZip);
                        //记录操作结果
                        result.add(new ResultObject(css, "s",""));                }
                    catch (Exception ex)
                    {
                        ROLog.getLog().error("Exception", ex);
                        //记录操作结果
                        String sto = (String) to.get(i);
                        sto = sto.substring(0, sto.length() - 1);
                        if("not contain".equals(ex.getMessage()))
                        {
                             result.add(new ResultObject(sto, "f","filetransfer.erromessage3"));
                        }
                        else if("Unzip".equals(ex.getMessage()))
                          {
                            result.add(new  ResultObject(sto, "f","filetransfer.erromessage4"));
                           }
                         else
                        {
                           result.add(new ResultObject(sto, "f","filetransfer.erromessage1"));
                        }                }            }        }        finally
            {
                //删除本地临时文件
                if (din != null)
                {
                    din.close();
                }
                remove(localZip);        }        return result;
        }