日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java高级语法笔记-文件读写

發布時間:2025/3/15 java 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java高级语法笔记-文件读写 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫文件:追加模式寫入
在構造時第2個參數置為true,表示append

new FileOutputStream(filename, true);


使用FileInputStream可以從文件中讀取數據
// 設置一個大的緩沖區
byte[] buf = new byte[1024];
// 打開文件,把數據讀到緩沖區里
FileInputStream fin = new FileInputStream(filename);
count = fin.read(buf, 0, 1024);
fin.close();


代碼如下:

package my;import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer;public class HelloWorld {//寫文件測試public static void test1() {byte[] data= {1,2,3,4,5,6};File filename=new File("c:/example/haha");try {FileOutputStream fout=new FileOutputStream(filename);fout.write(data);fout.close();}catch(IOException e) {e.printStackTrace();}}//指定數據偏移寫入public static void test2() {byte[]data= {1,2,3,4,5,6};File filename=new File("c:/example/haha");try {FileOutputStream fout=new FileOutputStream(filename);fout.write(data, 1, 2);fout.close();}catch(IOException e) {e.printStackTrace();}}public static void write(byte[] data) {File filename=new File("c:/example/haha2");try {FileOutputStream fout=new FileOutputStream(filename);fout.write(data);fout.close();}catch(IOException e) {e.printStackTrace();}}public static int read(byte[] buf,String n) {int count=0;File filename=new File(n);try {FileInputStream fin=new FileInputStream(filename);count=fin.read(buf);fin.close();}catch(IOException e) {e.printStackTrace();}return count;}//讀文件測試public static void test3() {byte[] buf=new byte[1024];int count=0;File filename=new File("c:/example/haha");try {FileInputStream fin=new FileInputStream(filename);count=fin.read(buf,0,1024);fin.close();}catch(IOException e) {e.printStackTrace();}System.out.println("test3:讀取haha文件獲取:"+count+"bytes");}public static void main(String[] args){ //test1();//test2();//test3();String str="你好,中國!";try {byte[] data=str.getBytes("GBK"); write(data);}catch(UnsupportedEncodingException e) {e.printStackTrace();}byte[] buf=new byte[1024];int n=read(buf,"c:/example/haha2");try {String strRead=new String(buf,0,n,"GBK");System.out.println("got:"+strRead);}catch(UnsupportedEncodingException e) {e.printStackTrace();}} }
運行結果如下:



總結

以上是生活随笔為你收集整理的Java高级语法笔记-文件读写的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。