Java高级语法笔记-文件读写
生活随笔
收集整理的這篇文章主要介紹了
Java高级语法笔记-文件读写
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫文件:追加模式寫入
在構造時第2個參數置為true,表示append
運行結果如下:
在構造時第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高级语法笔记-文件读写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php符号 set,PHP 符号大全
- 下一篇: Java高级语法笔记-HashMap