java讀寫檔案操作

來源:互聯網
上載者:User

將字串寫入檔案:

Code:
  1. import java.io.*;  
  2.   
  3. class FileOutputDemo {  
  4.     public static void main(String args[]) {  
  5.         FileOutputStream out; // declare a file output object  
  6.         PrintStream p; // declare a print stream object  
  7.   
  8.         try {  
  9.             // connected to "myfile.txt "  
  10.             out = new FileOutputStream("C:/a.txt");  
  11.             // Connect print stream to the output stream  
  12.             p = new PrintStream(out);  
  13.             p.println("This   is   written   to   a   file ");  
  14.             p.close();  
  15.         } catch (Exception e) {  
  16.             System.err.println("Error   writing   to   file ");  
  17.         }  
  18.     }  
  19. }  

java讀取檔案內容:

Code:
  1. import java.io.*;  
  2.   
  3. class FileInputDemo {  
  4.     public static void main(String args[]) {  
  5.         // args.length is equivalent to argc in C  
  6.             try {  
  7.                 // Open the file that is the first command line parameter  
  8.                 FileInputStream fstream = new FileInputStream("C:/b.txt");  
  9.                 // Convert our input stream to a DataInputStream  
  10.                 DataInputStream in = new DataInputStream(fstream);  
  11.                 // Continue to read lines while there are still some left to  
  12.                 // read  
  13.                 String s = "";  
  14.                 while (in.available() != 0) {  
  15.                     // Print file line to screen  
  16.                     s=in.readLine();  
  17.                     System.out.println(s);  
  18.                 }  
  19. //               String regex="src=/"";   
  20. //               s=s.replaceAll(regex,"str=/"http://article.star.com:8081/temp/");   
  21.                 in.close();  
  22.             } catch (Exception e) {  
  23.                 System.err.println("File   input   error ");  
  24.             }  
  25.           
  26.     }  
  27. }  

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.