1. 程式人生 > 其它 >Java字串寫入檔案的方式

Java字串寫入檔案的方式

技術標籤:javajavaFile

Java將字串寫入檔案,一般使用FileWriter或FileOutputStream類,下面分別給出示例:

一、使用FileWriter類

   @Test
    public void fileWriterTest() {
        String str="hello world!\nhello world!\nhello world!";
        FileWriter writer;
        try {
            writer = new FileWriter("testFileWriter.txt"); // 如果已存在,以覆蓋的方式寫檔案
            // writer = new FileWriter("testFileWriter.txt", true); // 如果已存在,以追加的方式寫檔案
            writer.write(""); //清空原檔案內容
            writer.write(str);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意:如果使用追加的方式寫檔案,那麼FileWriter的第2個引數要置為true。

二、使用FileOutputStream類

@Test
    public void fileOutPutStreamTest() {
        String str="hello world!\nhello world!\nhello world!";
        File txt;
        FileOutputStream fos;
        try {
            txt = new File("testFileOutPutStream.txt");
            if(!txt.exists()) {
                boolean newFile = txt.createNewFile();
                if (!newFile) {
                    System.out.println("fail to create new file, please check!");
                    return;
                }
            }
            byte[] bytes = str.getBytes();
            int b = bytes.length;   //是位元組的長度,不是字串的長度
            fos = new FileOutputStream(txt); // 如果已存在,以覆蓋的方式寫檔案
            // fos = new FileOutputStream(txt, true); // 如果已存在,以追加的方式寫檔案
            fos.write(bytes,0, b); // 寫指定長度的內容
            // fos.write(bytes); // 寫全文
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意:如果使用追加的方式寫檔案,那麼FileOutputStream的第2個引數要置為true。