1. 程式人生 > >java中io建立檔案和讀取檔案

java中io建立檔案和讀取檔案

簡單瞭解IO流:https://www.cnblogs.com/weibanggang/p/10034325.html

package com.wbg.iodemo1128;

import java.io.*;

public class OutputStreamDemo {
    public static void main(String[] args) throws IOException {
        reader();
    }
    //輸入位元組流OutputStream
    static void inputStream() throws IOException {
        File f
=new File("F:"+File.separator+"test01.txt"); InputStream inputStream=new FileInputStream(f); byte b[]=new byte[1024]; inputStream.read(b); inputStream.close(); System.out.println(new String(b)); } //輸出位元組流OutputStream static void outputStream()throws IOException{
//第一步:使用File找到一個檔案 File f=new File("F:"+File.separator+"test01.txt"); //建立檔案 f.createNewFile(); //第二步:通過子類例項化父類物件 OutputStream out=new FileOutputStream(f); //第三步:寫一個字串 String str="Hello World!!!"; //第四步:字串轉為byte陣列 byte b[]=str.getBytes();
//第五步:內容輸出 out.write(b); //第六步:關閉 out.close(); } //字元流輸出 static void writer() throws IOException { //第一步:使用File找到一個檔案 File f=new File("f:"+File.separator+"test.txt"); //第二步:通過子類例項化父類物件 Writer out=new FileWriter(f); //追加 // Writer out=new FileWriter(f,true); //第三:定義字串 String str="Hello,Word!!!"; //第四步:輸出 out.write(str); //第五步:強制清空快取 out.flush(); //第六步:關閉 out.close(); } //字元流正常輸入 static void reader() throws IOException { //第一步:使用File找到一個檔案 File f=new File("f:"+File.separator+"test.txt"); Reader readerout=new FileReader(f); int len=0; char[]c=new char[1024]; int temp=0; while ((temp=readerout.read())!=-1){ c[len]=(char)temp; len++; } readerout.close(); System.out.println(new String(c,0,len)); } //字元流輸入追加 static void readerAdd() throws IOException { File f=new File("f:"+File.separator+"test.txt"); Reader reader=new FileReader(f); char[]c=new char[(int)f.length()]; reader.read(c); reader.close(); System.out.println(new String(c)); } }