Chinaunix首页 | 论坛 | 博客
  • 博客访问: 807904
  • 博文数量: 780
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5010
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:11
文章分类

全部博文(780)

文章存档

2011年(1)

2008年(779)

我的朋友
最近访客

分类:

2008-09-12 09:14:20

    /**

         * 将指定的文本内容写入到指定路径的文件

         * @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]);

                    }

 

 

[1]  

【责编:landy】

--------------------next---------------------

阅读(375) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~