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();
    }
    //輸入字節流inputStream
    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));
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM