写入指定长度的字节到文件

使用java ,如何把指定长度的字节写入文件呢,或者说如何从inputStream 中读取指定长度的字节写入outputStream中呢?

/***
	 * write inputstream into file according to specified length.
	 * 
	 * @param file
	 * @param ins
	 *            : not closed
	 * @param length2
	 * @throws IOException
	 */
	public static FileOutputStream writeInputStream2File(File file,
			InputStream ins, long length2, boolean isCloseOutputStream)
			throws IOException {
		String parentDir = SystemHWUtil.getParentDir(file.getAbsolutePath());
		File fatherFile = new File(parentDir);
		if (!fatherFile.exists()) {
			fatherFile.mkdirs();
		}
		FileOutputStream outs = new FileOutputStream(file);
		int readSize;
		byte[] bytes = null;
		bytes = new byte[(int) length2];

		long length_tmp = length2;
		while ((readSize = ins.read(bytes)) != SystemHWUtil.NEGATIVE_ONE/*-1*/) {
			length_tmp -= readSize;

			outs.write(bytes, 0, readSize);
			if (length_tmp == 0) {
				break;
			}
			//非常重要,千万不能去掉!!!
			 if (length_tmp < SystemHWUtil.BUFF_SIZE/*4096*/) {
			 bytes = new byte[(int) length_tmp];
			 }
		}
		outs.flush();
		if (isCloseOutputStream) {
			outs.close();
		}
		return outs;
	}

/***
	 * Not responsible for closing the output and input stream 写入指定长度的字节到输出流
	 * 
	 * @param fin
	 * @param fout
	 *            : The divided file
	 * @param length2
	 * @throws IOException
	 */
	public static void writeFromFile2File(InputStream fin, OutputStream fout,
			long length2) throws IOException {
		
		if (length2 == 0) {// want to write zero bytes
			// if (fout != null) {
			// fout.close();
			// }
			return;
		}
		int readSize;
		byte[] bytes = null;
		if (length2 >= SystemHWUtil.BUFF_SIZE) {
			bytes = new byte[SystemHWUtil.BUFF_SIZE];
		} else {
			bytes = new byte[(int) length2];
		}

		long length_tmp = length2;
		while ((readSize = fin.read(bytes)) != SystemHWUtil.NEGATIVE_ONE) {
			
			length_tmp -= readSize;
			fout.write(bytes, 0, readSize);
			if (length_tmp == 0) {
				break;
			}
			//非常重要,千万不能删除
			 if (length_tmp < SystemHWUtil.BUFF_SIZE) {
			 bytes = new byte[(int) length_tmp];
			 }
		}

	}

	/***
	 * Responsible for closing the output stream
	 * 
	 * @param fin
	 * @param outPutFile
	 * @param length2
	 *            :The number of bytes to be written
	 * @param append
	 *            : Whether additional
	 * @throws IOException
	 */
	public static void writeFromFile2File(FileInputStream fin, File outPutFile,
			long length2, boolean append) throws IOException {
		
		if (length2 == 0) {// want to write zero bytes
			return;
		}
		FileOutputStream fout = null;
		try {
			fout = new FileOutputStream(outPutFile, append/* 追加 */);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		try {
			writeFromFile2File(fin, fout, length2);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			fout.flush();
			fout.close();// Close the stream
		}
	}

 上述代码见附件中io0007-find_progess\src\main\java\com\io\hw\file\util\FileUtils.java

依赖的包:is_chinese-0.0.2-SNAPSHOT.jar

参考:http://hw1287789687.iteye.com/blog/2023095

写入文件:

/***
	 * 写入文件
	 * @param content
	 * @param charset
	 * @param readAndWriteResult
	 * @param file
	 * @throws IOException
	 */
	private static void writeStubFile(String content, String charset,  File file) throws IOException {
		FileWriterWithEncoding fileW = new FileWriterWithEncoding(file, charset);
		fileW.write(content);
		fileW.close();
		
	}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用`RandomAccessFile`类以及`MappedByteBuffer`来指定位置写入文件。首先,你需要创建一个`RandomAccessFile`对象,并使用`"rw"`模式打开文件。然后,调用`getChannel()`方法获取文件的`FileChannel`对象。接下来,你可以使用`FileChannel`的`map()`方法创建一个`MappedByteBuffer`,并指定写入的位置和长度。 下面是一个示例代码: ```java import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { try { RandomAccessFile file = new RandomAccessFile("example.txt", "rw"); FileChannel channel = file.getChannel(); int position = 10; // 指定写入的位置 int size = 15; // 写入字节长度 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, position, size); // 写入数据到MappedByteBuffer String data = "Hello, World!"; buffer.put(data.getBytes(StandardCharsets.UTF_8)); // 关闭文件和通道 channel.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,我们打开了一个名为`example.txt`的文件,并将文件的第10个字节开始的15个字节映射到`MappedByteBuffer`。然后,我们使用`put()`方法将字符串"Hello, World!"写入到`MappedByteBuffer`中。 请注意,使用`MappedByteBuffer`时需要保证指定的位置和长度不超过文件的大小,否则可能会抛出`IndexOutOfBoundsException`异常。另外,一旦将数据写入到`MappedByteBuffer`中,它会自动反映到文件中,你不需要手动执行写入操作。 希望这可以帮助到你!如果有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值