將指定的文本內容寫入到指定路徑的文件

/**

     * 將指定的文本內容寫入到指定路徑的文件

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

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章