java寫入文件,java寫入文件buffer writer

本文目錄一覽:

java如何寫入文件

package filewriter;  

  

import java.io.FileWriter;  

import java.io.IOException;  

  

public class IOExceptionDemo {  

  

    private static final String LINE_SEPARATOR = System.getProperty(“line.separator”);  

    public static void main(String[] args) {  

  

        FileWriter fw = null;  

        try {  

            fw = new FileWriter(“k:\\Demo.txt”, true);  

            fw.write(“hello” + LINE_SEPARATOR + “world!”);  

        } catch (Exception e) {  

            System.out.println(e.toString());  

        } finally {  

            if (fw != null)  

                try {  

                    fw.close();  

                } catch (IOException e) {  

                    throw new RuntimeException(“關閉失敗!”);  

                }  

        }  

    }  

}

Java的文件生成然後寫入

創建文件

new File(文件路徑).createNewFile();這是寫入文件

try{

FileOutputStream filewrite = new FileOutputStream(文件路徑); //這個要捕捉異常

filewrite.write(要寫入的數據byte[]);

filewrite.close();

}catch(IOException e);

java 怎麼將數據寫入TXT文件

定義一個輸出文件,然後輸出就可以了,具體見下面的代碼

 import java.io.*;

 public class StreamDemo

 {

  public static void main(String args[])

  {

   File f = new File(“c:\\temp.txt”) ;

   OutputStream out = null ;

   try 

   {

    out = new FileOutputStream(f) ;

   } 

   catch (FileNotFoundException e) 

   {

    e.printStackTrace();

   }

   // 將字符串轉成位元組數組

   byte b[] = “Hello World!!!”.getBytes() ;

   try 

   {

    // 將byte數組寫入到文件之中

    out.write(b) ;

   } 

   catch (IOException e1) 

   {

    e1.printStackTrace();

   }

   try 

   {

    out.close() ;

   } 

   catch (IOException e2) 

   {

    e2.printStackTrace();

   }

  

   // 以下為讀文件操作

   InputStream in = null ;

   try 

   {

    in = new FileInputStream(f) ;

   } 

   catch (FileNotFoundException e3) 

   {

    e3.printStackTrace();

   }

   // 開闢一個空間用於接收文件讀進來的數據

   byte b1[] = new byte[1024] ;

   int i = 0 ;

   try 

   {

   // 將b1的引用傳遞到read()方法之中,同時此方法返回讀入數據的個數

    i = in.read(b1) ;

   } 

   catch (IOException e4) 

   {

    e4.printStackTrace();

   }

   try 

   {

    in.close() ;

   } 

   catch (IOException e5) 

   {

    e5.printStackTrace();

   }

   //將byte數組轉換為字符串輸出

   System.out.println(new String(b1,0,i)) ;

  }

 }

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/295502.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-27 12:56
下一篇 2024-12-27 12:56

相關推薦

發表回復

登錄後才能評論