当前位置:首页 » 编程语言 » java文件二进制

java文件二进制

发布时间: 2022-05-26 23:29:48

‘壹’ java中二进制怎么表示

二进制是计算技术中广泛采用的一种数制。二进制数据是用0和1两个数码来表示的数。它的基数为2,进位规则是“逢二进一”,借位规则是“借一当二”,由18世纪德国数理哲学大师莱布尼兹发现。当前的计算机系统使用的基本上是二进制系统,数据在计算机中主要是以补码的形式存储的。计算机中的二进制则是一个非常微小的开关,用“开”来表示1,“关”来表示0。
1、Java中定义两个数,然后分别打印出它们的二进制表示:
System.out.println("Java二进制7: "+Integer.toBinaryString(7));
System.out.println("Java二进制-7: "+Integer.toBinaryString(-7));
输出:
Java二进制7:
111
Java二进制-7:

可以看到Java中对于数的表示属于有符号的,那么这个是怎么来的?
7好办,直接是111
-7转化二进制的过程:
(1)把-7转化成7,二进制是
111
(2)Java中对于不满32位的int二进制自动补齐,所以变成了
(29个0)111
(3)然后取反
(29个1)000
(4)然后加1
(29个1)001
这就是-7的整个转化过程,那么现在有一个问题,如果有一个文本文件,每一行有八位二进制,表示的范围是(0~255),也就是用一个字节表示的无符号整数,如果现在要把这些二进制转化成整数存到文件里应该怎么做?
文件:
line1

11111110

(254)
line2

00000000

(0)
假设用Java读进了第一行,那么直接打印出来的值是-2,不符合要求,这时让-2变254有两种办法:
(1)用Java自带的方法,Byte.toUnsignedInt((byte)
-2)(ps.-2的二进制表示就是line1),这样打印出来的就是254了
System.out.println(Byte.toUnsignedInt((byte) -2));
输出:254
第二种方法的原理:
Java中-2的二进制表示:(这个二进制的后八位就是line1,可以直接打印的话Java把其当做了负数
-2)
Java中255的二进制表示:(24个‘0’,8个‘1’)
做与后变为:
这样做与后表示的数就是正数了
254。可以想一下,假设每一行用2个字节表示一个无符号数,那么可以把每一行变成正整数用方法2怎么做?
2.Java中的>>和>>>
'>>'
算术右移,向右移左边补符号位
'>>>'
逻辑右移,向右移左边补0
System.out.println("Java二进制-7: "+Integer.toBinaryString(-7));
System.out.println("-7>>2: "+Integer.toBinaryString(-7>>2));
System.out.println("-7>>>2: "+Integer.toBinaryString(-7>>>2));输出:
Java二进制-7:
-7>>2:
-7>>>2: //正常应该这样(00)左边的两个0不显示

‘贰’ JAVA中读取文件(二进制,字符)内容的几种方

JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代码,需要的可以直接复制使用

public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}

} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}

/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}

‘叁’ java编译器把java程序编译成虚拟机可以识别的二进制代码,称为什么

由java编译器把源文件编译成虚拟机可以识别的二进制代码称为字节码。

而字节码是由java解释器去解释执行的。

‘肆’ java中什么是能够在计算机CPU上执行的二进制代码

java中的JVM是能够在计算机CPU上执行的二进制代码。

  • java的执行过程

Java代码需要经过编译和解释两个步骤,才在能在平台上运行。首先java语言的编译器,帮java代码编译成class的字节码,之后通过java虚拟机(JVM)来解释执行。

  • java代码的编译

java代码是如何编译的?

首先编译的解释:把用高级程序设计语言书写的源程序,翻译成等价的计算机汇编语言或机器语言书写的目标程序的翻译程序。编译的具体过程,可以看看《编译原理》相关的书籍。

其实java的编译过程,和通常c/c++还是不同的。

java编译后的字节码文件格式主要分为两部分:常量池和方法字节码。常量池记录的是代码出现过的所有token(类名,成员变量名等等)以及符号引用(方法引用,成员变量引用等等);方法字节码放的是类中各个方法的字节码。

Java编译器却不将对变量和方法的引用编译为数值引用,也不确定程序执行过程中的内存布局,而是将些符号引用信息保留在字节码中,由解释器在运行过程中创立内存布局,然后再通过查表来确定一个方法所在的地址,这样就有效地保证了java的可移植性和安全性。

c/c++的编译,当C编译器编译生成一个对象的代码时,该代码是为在某一特定硬件平台运行而生成的。因此在编译过程中,编译程序通过查表将所有对符号的引用转换为特定的内存偏移量,以保证程序运行。

  • java虚拟机(JVM)

简单的可以这样理解它的功能:就是将java编译之后的字节码,解释成cpu能够执行的二进制代码。

JVM是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。JVM有自己完善的硬件架构,如处理器、堆栈、寄存器等,还具有相应的指令系统。JVM的主要工作是解释自己的指令集(即字节码)并映射到本地的CPU的指令集或OS的系统调用。Java语言是跨平台运行的,其实就是不同的操作系统,使用不同的JVM映射规则,让其与操作系统无关,完成了跨平台性。JVM对上层的Java源文件是不关心的,它关注的只是由源文件生成的类文件(class file)。类文件的组成包括JVM指令集,符号表以及一些补助信息。

java虚拟机工作的原理,可以自己找一下网上的资料。大家还需要思考的问题,jvm的内存、jvm的垃圾回收(GC)、Android的朋友还要区分(Dalvik 和标准 Java 虚拟机JVM)的区别。

  • 总结:

java代码编译之后,可以直接运行在Windows或者其它装有JVM虚拟机的系统下。而C或C++直接编译成与机器和操作系统相关的代码。所以C语言编译的程序没有跨平台性,就算没有使用到操作系统相关的API,在不同的系统下也必须重新编译才能运行。

‘伍’ java实现解析二进制文件

/**
*
*/
package com.igen.case10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

/**
*
* @ClassName Case10
* @Description TODO
*
* @author wjggwm
* @data 2017年2月7日 上午11:46:25
*/
public class Case10 {

static final String fileName = "/test.png";
static final String filePath = "D:/files/case10";
static final String sourceFileName = "binary";

public static void main(String[] args) {
try {
readFile(Case10.class.getResource(sourceFileName).toURI().getPath());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}

/**
*
* @Description 解析二进制文件
* @param sourceFileName
*
* @author wjggwm
* @data 2017年2月7日 上午11:47:12
*/
public static void readFile(String sourceFileName) {
InputStream in = null;
try {
in = new FileInputStream(sourceFileName);

// 读取字符串数据长度字节
byte[] txtLenByte = new byte[2];
in.read(txtLenByte);
int txtlen = byte2ToUnsignedShort(txtLenByte, 0);

// 读取字符串字节
byte[] txtByte = new byte[txtlen];
in.read(txtByte);
//字符串为UTF-8编码
String txt = new String(txtByte, "UTF-8");
// 输出字符串
System.out.println(txt);

// 读取图片数据长度
byte[] imgLenByte = new byte[4];
in.read(imgLenByte);
int imgLen = byte4ToInt(imgLenByte, 0);

// 读取图片数据
byte[] img = new byte[imgLen];
in.read(img);
// 生成图片文件
saveToImgByBytes(filePath, fileName, img);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

/**
*
* @Description 将字节写入文件
* @param imgName
* @param imgByte
*
* @author wjggwm
* @data 2017年2月7日 上午11:07:45
*/
public static void saveToImgByBytes(String filePath, String imgName, byte[] imgByte) {
try {
File dic = new File(filePath);
if (!dic.exists()) {
dic.mkdirs();
}
File image = new File(filePath + imgName);
if (!image.exists()) {
image.createNewFile();
}
FileOutputStream fos = new FileOutputStream(image);
fos.write(imgByte);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
* @Description byte数组转换为无符号short整数
* @param bytes
* @param off
* @return
*
* @author wjggwm
* @data 2017年2月7日 上午11:05:58
*/
public static int byte2ToUnsignedShort(byte[] bytes, int off) {
// 注意高位在后面,即大小端问题
int low = bytes[off];
int high = bytes[off + 1];
return (high << 8 & 0xFF00) | (low & 0xFF);
}

/**
*
* @Description byte数组转换为int整数
* @param bytes
* @param off
* @return
*
* @author wjggwm
* @data 2017年2月7日 上午11:07:23
*/
public static int byte4ToInt(byte[] bytes, int off) {
// 注意高位在后面,即大小端问题
int b3 = bytes[off] & 0xFF;
int b2 = bytes[off + 1] & 0xFF;
int b1 = bytes[off + 2] & 0xFF;
int b0 = bytes[off + 3] & 0xFF;
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}

}

‘陆’ java读取二进制文件

思路:按照字节读取文件到缓冲,然后对文件内容进行处理。

代码如下:


publicstaticvoidreadFile()throwsIOException{
RandomAccessFilef=newRandomAccessFile("test.txt","r");
byte[]b=newbyte[(int)f.length()];
//将文件按照字节方式读入到字节缓存
f.read(b);
//将字节转换为utf-8格式的字符串
Stringinput=newString(b,"utf-8");
//可以匹配到所有的数字
Patternpattern=Pattern.compile("\d+(\.\d+)?");
Matchermatch=pattern.matcher(input);
while(match.find()){
//match.group(0)即为你想获取的数据
System.out.println(match.group(0));
}
f.close();
}

‘柒’ java里怎样把文件转换成二进制

转换文件成为二进制数据并保存的Java代码:

取出数据并还原文件到本地的java代码:

[java]view plain//读取数据库二进制文件

publicvoidreaderJpg()throwssqlException

{

connection=connectionManager.getconn();//自己连接自己的数据库

StringsqlString="selectimagesfromsave_imagewhereid=4";//从数据库中读出要还原文件的二进制码,这里我读的是自己的数据库id为4的文件

Filefile=newFile("E:\1.jpg");//本地生成的文件

if(!file.exists())

{

try{

file.createNewFile();

}catch(Exceptione){

e.printStackTrace();

}

}

try{

byte[]Buffer=newbyte[4096*5];

statement=connection.prepareStatement(sqlString);

resultSet=statement.executeQuery();

if(resultSet.next())

{

FileOutputStreamoutputStream=newFileOutputStream(file);

InputStreamiStream=resultSet.getBinaryStream("images");//去字段用getBinaryStream()

intsize=0;

while((size=iStream.read(Buffer))!=-1)

{

System.out.println(size);

outputStream.write(Buffer,0,size);

}

}

}catch(Exceptione){

e.printStackTrace();

}

}

‘捌’ Java 一个文件里面存储的是二进制数据 读取出来以字符串形式展示

不需要转换。
解释:任何文件的存储都是通过二进制的形式进行存储的,只不过经过机器语言编译后,展示给用户的体验是中文或者是字符串形式。
备注:如果是想将数字转换为二进制,可以直接通过Integer的toBinaryString方法直接进行转换,举例:
int i =8;
System.out.println(Integer.toBinaryString(i));
输出结果就是:1000.

‘玖’ 怎样用Java读写二进制文件

import java.util.*;
import java.io.*;

class SmallFile {
static final int HEADLEN = 24; //头总长度
byte[] fileName = new byte[16]; //列表文件名1: 长度128 想把它读到char[]里 它的编码方式不是Unicode。在不确定编码方式的时候,最好直接用byte[]来存放
int offset; //列表文件地址1: 长度32 想把它读到int里
int length = -1; //列表文件长度1: 长度32 想把它读到int里
byte[] content;
public SmallFile() {

}

public SmallFile(byte[] fn, byte[] content) {
Arrays.fill(fileName, (byte) 0);
if (fn != null) {
if (fn.length <= 16) {
System.array(fn, 0, fileName, 0, fn.length);
}
else {
System.array(fn, 0, fileName, 0, 16);
}
}
this.content = content;
if (content != null) {
this.length = content.length;
}
else {
this.length = -1;
}
}
}

public class ReadBinary {
static final int HEADLEN = 8; //头总长度
private String filename;
private byte[] filehead = new byte[4]; //文件头: 长度32 想把它读到char[]里 它的编码方式不是Unicode
private int filecount = -1; //列表长度: 长度32 想把它读到int里 假设他是3 就会有3个列表文件名
private List<SmallFile> files = null;

public void setFilehead(byte[] fh) {
if (fh == null)
return;
Arrays.fill(filehead, (byte) 0);
if (fh.length <= 4) {
System.array(fh, 0, filehead, 0, fh.length);
}
else {
System.array(fh, 0, filehead, 0, 4);
}
}

public ReadBinary(String filename) {
try {
readFromFile(filename);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("在载入数据文件时失败,因此视同为新建一个数据文件!");
this.filename = filename;
Arrays.fill(filehead, (byte) 0);
filecount = 0;
files = new ArrayList<SmallFile> ();
}
}

public void readFromFile(String filename) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
filename));
this.filename = filename;
DataInputStream in = new DataInputStream(bin);
in.read(filehead); //文件头: 长度32 想把它读到char[]里 它的编码方式不是Unicode
filecount = in.readInt(); //列表长度: 长度32 想把它读到int里 假设他是3 就会有3个列表文件名
if (files == null) {
files = new ArrayList<SmallFile> ();
}
else {
files.clear();
}
for (int i = 0; i < filecount; i++) {
SmallFile file = new SmallFile();
in.read(file.fileName);
file.offset = in.readInt(); //列表文件地址1: 长度32 想把它读到int里
file.length = in.readInt(); //列表文件长度1: 长度32 想把它读到int里
files.add(file);
}
}

public void writeToFile() throws Exception {
String temp = filename + ".tmp"; //临时文件
boolean exists = false;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filename, "r"); //文件存在则从文件读入
exists = true;
}
catch (Exception ex) {
System.out.println("文件不存在,因此启用内存写入模式");
}
if (filecount != files.size()) {
throw new Exception("怪事,居然不相同??");
}
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new
FileOutputStream(temp)));
//1、写总文件头
out.write(filehead);
out.writeInt(filecount);
//2、写列表头
int sumlength = 0;
for (int i = 0; i < files.size(); i++) {
SmallFile file = files.get(i);
out.write(file.fileName);
if (file.length < 0) {
throw new Exception("怪事,文件长度怎么可能小于0?");
}
else {
out.writeInt(ReadBinary.HEADLEN + SmallFile.HEADLEN * filecount +
sumlength);
sumlength += file.length;
out.writeInt(file.length);
}
}
//3、写文件内容
for (int i = 0; i < files.size(); i++) {
SmallFile file = files.get(i);
if (file.content != null && (file.length == file.content.length)) {
out.write(file.content);
}
else if (exists) {
raf.seek(file.offset);
byte[] b = new byte[file.length];
raf.read(b);
System.out.println("b:" + new String(b));
out.write(b);
}
else {
throw new Exception("怪事,又不能从内存读,又不能从文件读。这活没法干了!");
}
}

out.close();
if (raf != null) {
raf.close();
raf = null;
}
System.gc();
//把原先的文件删除
File f = new File(filename);
f.delete();
//再把临时文件改名到正式文件
File f2 = new File(temp);
f2.renameTo(f);
}

public void addFile(SmallFile file) {
if (files != null) {
filecount++;
files.add(file);
}
}

public static void test1(){
ReadBinary rb = new ReadBinary("f:\\temp\\rb.dat");
rb.setFilehead("".getBytes());
SmallFile f = new SmallFile("第1个文件".getBytes(), "第1个文件的内容".getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static void test2(){
ReadBinary rb = new ReadBinary("f:\\temp\\rb.dat");
rb.setFilehead("HEA".getBytes());
SmallFile f = new SmallFile("第2个文件".getBytes(), "第2个文件的内容".getBytes());
rb.addFile(f);
try {
rb.writeToFile();
}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {
//test1();
test2();
}
}

热点内容
怎么创建密码重置盘 发布:2025-02-12 16:36:59 浏览:675
php读取时间 发布:2025-02-12 16:23:48 浏览:385
祛痘液如何配置 发布:2025-02-12 16:21:22 浏览:748
安卓手机如何拷贝电脑里 发布:2025-02-12 16:16:30 浏览:860
linux怎么编译内核 发布:2025-02-12 16:03:02 浏览:189
新的怎么注册微信账号密码忘了怎么办 发布:2025-02-12 15:50:08 浏览:659
android代码搜索 发布:2025-02-12 15:45:36 浏览:779
矢量图算法 发布:2025-02-12 15:43:53 浏览:193
python量化投资入门 发布:2025-02-12 15:34:17 浏览:175
苹果的天气跟安卓的天气哪个准 发布:2025-02-12 15:33:37 浏览:314