c++&python&JAVA 读写二进制&文本文件

6 篇文章 0 订阅

c++读写文本文件

// 写
std::ofstream fout("a.txt");
int nNum = 20;
std::string str("hello");
fout << nNum << "," << std << std::endl;
fout.close()

// 读文本文件
std::ifstream fin("a.txt");
int nNum;
char szBuf[256] = {0};

fin >> nNum >> szBuf;
fin.close();

c++读写二进制文件

#include <fstream>

// 写二进制
std::ofstream fout("data.dat", std::ios::binary);
int nNum = 20;
int a[5] = {1, 2, 3, 4, 5};
std::string str("hello, world");

fout.write((char*)&nNum, sizeof(int));
fout.write(reinterpret_cast<const char*>(a), sizeof(int)*5);
fout.write(str.c_str(), sizeof(char)*(str.size()));
fout.close();

// 读二进制文件
std::ifstream fin("data.dat", std::ios::binary);
int nNum;
int b[5];
char szBuf[256] = {0};

fin.read((char*)&nNum, sizeof(int));
fin.read(reinterpret_cast<char*>(b), sizeof(int)*5);
fin.read(szBuf, sizeof(char) * 256);
fin.close();

参考:C++读写二进制文件

// 获取文件的大小
ifstream fin;
fin.open("test.jpg", ios::binary | ios.ate);
long size = fin.tellg();

参考:[C++]读写二进制文件和文本文件

python读写文本文件

f = open('test.txt')
f.read()
f.close()

f.readline() # 整行读取数据,若没读取到数据则返回空
f.readlines() # 将文件内容以列表形式存放
f.next() # 和f.readline()相似,逐行读取数据,若没读取到数据则报错

# 写入txt, 文件如果存在会先清空再写入
f = open('test.txt', 'w', buffering=1) # 行缓冲,python3文本读写不能使用无缓冲,但二进制写可以使用buffering=0
f.write('hello')
f.close()

f.writelines(['\nhello dear!', '\nhello baby!']) # 多行写入

参考:Python读写txt文本文件

python读写二进制文件

  • np.save & np.load 将数组以未压缩的原始二进制格式保存在扩展名为 npy 的文件中
np.save('name.npy', data)
data = np.load('name.npy')
  • tofile & fromfile 读写二进制文件。文件后缀名没有要求,且读取数据需要指定 dtype ,需要与保存时的类型一致。
data.tofile("data.bin")
data = np.fromfile("data.bin", dtype=np.float32)

参考:Numpy数组的保存与读取

JAVA写二进制文件

  • 注意需要放在try-catch里,否则会报错unhandled exception: java.io.filenotfoundexception
public static void writeFile(String path, String fileName, byte[] content)
		throws IOException {
	try {
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		FileOutputStream fos = new FileOutputStream(path + fileName);
		fos.write(content);
		fos.close();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}

参考:
[1] JAVA文件工具类之——文件写入(byte数组、String方式、url写入方式)

JAVA获取png的图像数据并以rgbrgb格式存储为byte数组

FileInputStream img = new FileInputStream("img.png");
Bitmap bitmap = BitmapFactory.decodeStream(img);
int[] pixels = new int[width * height]; 
byte[] data = new byte[width * height * 3];

bitmap.getPixels(pixels, 0, stride, 0, 0, width, height); // 读取图像数据,放入int数组中,int数组中的每个int数据包含rgb三个分量
for (int i = 0; i < pixels.length; ++i) {
	int pixel = pixels[i];
//  data[i * 3] = pixel >> 16 & 0xff;
	data [i * 3] = (byte)Color.red(pixel);
	data [i * 3 + 1] = (byte)(pixel >> 8 & 0xff);
	data [i * 3 + 2] = (byte)(pixel & 0xff);
}
// 读取png图像以rgba格式存储为byte数组
FileInputStream img = new FileInputStream("img.png");
Bitmap bitmap = BitmapFactory.decodeStream(img);
int pixel = bitmap.getPixel(0, 0);
int a = Color.alpha(pixel);
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);

int bytes = bitmap.getByteCount(); // 获取bitmap数据大小,存储的是argb数据
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer); // 复制数据
buffer.position(0);
byte[] bb = new byte[buffer.remaining()];
buffer.get(bb);  // bb中存储的是rgbargba...数据
// 一些Bitmap相关操作
int bytes = bitmap.getByteCount(); // Bitmap像素点的色彩通道排列顺序是RGBA
ByteBuffer buffer = ByteBuffer.allocate(bytes); //  使用allocate()静态方法创建字节缓冲区
bitmap.copyPixelsToBuffer(buffer); // 将位图的像素复制到指定的缓冲区

int w = bmp.getWidth();
int h = bmp.getHeight();

//byte 与 int 的相互转换
public static byte intToByte(int x) {
	return (byte) x;
}

public static int byteToInt(byte b) {
	//Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值
	return b & 0xFF;
}
 

参考:
[1] RGB和Bitmap互相转换
[2] android利用BitMap获得图片的像素数据
[3] 【Android】二进制图片和Bitmap的getPixel方法解析
[4] Java 中 byte、byte 数组和 int、long 之间的转换

C++中的文本文件二进制文件也有类似Python的区别。下面是一些代码示例,来说明二者的不同之处。 文本文件读写: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { // 打开文件 ofstream outfile("textfile.txt"); // 写入数据 outfile << "Hello World!" << endl; // 关闭文件 outfile.close(); // 打开文件 ifstream infile("textfile.txt"); // 读取数据 string text; while (getline(infile, text)) { cout << text << endl; } // 关闭文件 infile.close(); return 0; } ``` 在这个示例中,我们使用 `ofstream` 和 `ifstream` 两个类来分别写入和读取文本文件。`ofstream` 用于写入文件,`ifstream` 用于读取文件。在写入文件时,我们可以使用 `<<` 操作符将数据写入文件,这里我们写入了一个字符串 "Hello World!" 和一个换行符。在读取文件时,我们使用 `getline()` 函数来逐行读取文件中的内容,然后输出到控制台上。 二进制文件的读写: ```c++ #include <iostream> #include <fstream> using namespace std; struct Person { char name[20]; int age; }; int main() { // 创建结构体数据 Person person = {"Tom", 23}; // 打开文件 ofstream outfile("binaryfile.bin", ios::out | ios::binary); // 写入数据 outfile.write(reinterpret_cast<char*>(&person), sizeof(Person)); // 关闭文件 outfile.close(); // 打开文件 ifstream infile("binaryfile.bin", ios::in | ios::binary); // 读取数据 Person person2; infile.read(reinterpret_cast<char*>(&person2), sizeof(Person)); // 关闭文件 infile.close(); // 输出数据 cout << "Name: " << person2.name << endl; cout << "Age: " << person2.age << endl; return 0; } ``` 在这个示例中,我们使用结构体 `Person` 来存储数据,并将其写入二进制文件。在写入文件时,我们使用 `write()` 函数来写入数据。需要注意的是,由于二进制文件不是文本文件,因此我们需要将结构体的指针转换为字符指针,即使用 `reinterpret_cast<char*>()` 进行类型转换。在读取文件时,我们使用 `read()` 函数来读取数据,同样需要进行类型转换。最后,我们输出读取的数据。 总的来说,文本文件二进制文件都有各自的优缺点,应根据实际需求来选择使用哪种类型的文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值