将指定的文本内容写入到指定路径的文件
2008-07-04 17:31
519 查看
/** * 将指定的文本内容写入到指定路径的文件 * @param path 目标文件路径 * @param content 需要写入的内容 * @return 写入结果 */ public static boolean writeToFile(String path, String content) { final int CACHE = 1024; boolean result = false; FileOutputStream outFile = null; FileChannel channel = null; // 将字符串转换为字节数组 final byte[] bt = content.getBytes(); ByteBuffer buf = null; try { outFile = new FileOutputStream(path); channel = outFile.getChannel(); // 以指定的缓存分隔字节数组,得到缓存次数 int size = bt.length / CACHE; // 得到被缓存分隔后剩余的字节个数 int mod = bt.length % CACHE; int start = 0; int end = 0; for(int i = 0; i < size + 1; i++) { if(i == size) { if(mod > 0) { // 分配新的字节缓冲区 buf = ByteBuffer.allocate(mod); start = end; end += mod; } else { break; } } else { // 分配新的字节缓冲区 buf = ByteBuffer.allocate(CACHE); start = end; end = (i + 1) * CACHE; } // 以指定的始末位置获取一个缓存大小的字节 byte[] bytes = getSubBytes(bt, start, end); for(int j = 0; j < bytes.length; j++) { buf.put(bytes[j]); } // 反转缓冲区,为通道写入做好准备 buf.flip(); // 利用通道写入文件 channel.write(buf); result = true; } } catch(IOException e) { e.printStackTrace(); } finally { // 关闭所有打开的IO流 try { channel.close(); outFile.close(); } catch(IOException e) { e.printStackTrace(); } } return result; } /** * 以指定的始末位置从字节数组中获取其子数组 * @param bt 原始字节数组 * @param start 起始位置 * @param end 结束位置 * @return 子字节数组 */ private static byte[] getSubBytes(byte[] bt, int start, int end) { int size = end - start; byte[] result = new byte[size]; for(int i = 0; i < size; i++) { result[i] = bt[i + start]; } return result; }
相关文章推荐
- java在指定路径下创建文件,并写入文件内容
- asp.net创建并写入文本和读取文件内容
- C# 如何创建一个xml文件?并写入指定内容?
- Java读取和写入文本文件内容
- 替换一个文本文件中的指定内容
- [Java] 利用xpdf库获取pdf文件的指定范围文本内容
- JS基于FileSystemObject创建一个指定路径的TXT文本文件
- 文件的读取和写入(指定路径)
- IO流将指定内容写入指定目录文件内
- 如何自定义安装office 2016(通过configuration.xml文件来指定安装内容和路径)
- C++往txt文本文件里面写入内容
- C# 如何创建一个xml文件?并写入指定内容?
- 算法积累:解决如何获取指定文件夹路径或者文件路径下所有子文件后缀为.h .m .c的文本的行数
- python脚本-指定目录针对特定后缀名文件进行文本内容搜索
- [Java] 利用xpdf库获取pdf文件的指定范围文本内容
- 批处理递归指定目录下文件写入内容
- java按指定编码写入和读取文件内容的类
- java按指定编码写入和读取文件内容的
- Python读取指定路径所有.txt文件,将文件名写入.txt
- 算法积累:解决如何获取指定文件夹路径或者文件路径下所有子文件后缀为.h .m .c的文本的行数