java 文件的寫入與讀出

文件寫入

try {
            FileOutputStream fileout = new FileOutputStream(f1);
            String outstr = "這是寫入文件的數據";
            byte buf[] = outstr.getBytes();
            fileout.write(buf);
            fileout.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

文件的讀出

try {
            FileInputStream filein = new FileInputStream(f);
            byte[] buf = new byte[1024];
            String instr ="";
            int length = filein.read(buf);
            instr = new String(buf,0,length);
            System.out.println(instr);
            filein.close();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

將一個文件中的內容複製到文件2

public static void main(String[] args)
    {
        File f1 = new File("E:\\temp.txt");
        File f2 = new File("E:\\temp2.txt");
        FileInputStream fin = null;
        FileOutputStream fout = null;
        FileInputStream fin2 = null;
        try {
            fin = new FileInputStream(f1);
            byte[] buf = new byte[10240];
            int length = fin.read(buf);
            String str = new String(buf,0,length);
            System.out.println("文件1"+str);
            System.out.println(fin.getFD());
            try {
                fout = new FileOutputStream(f2);
                byte[] buf2 = str.getBytes();
                fout.write(buf2, 0, length);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally {
                try {
                    fout.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                fin.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        try {
            fin2 =new FileInputStream(f2);
            byte[] buf3 = new byte[10240];
            int length2 = fin2.read(buf3);
            String str2 = new String(buf3,0,length2);
            System.out.println("文件2"+str2);
            System.out.println(fin2.getFD());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                fin2.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章