package com.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class FileOutputStreamDemo { /** * @Title * @Description * @param * @return void * @throws IOException * @pages * @throws */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //須要讀取的字符串 String sourse = "Now is the time for all good men\n" +"to come to the aid of their country\n" +"and pay their due taxes."; //將字符串轉換爲字節數組 // File file = new File("file1.txt"); // byte[] buf=sourse.getBytes(); // OutputStream out; // try { // out = new FileOutputStream(file); // //將字節數組一半的內容寫入文件file1.txt // for(int i=0;i<buf.length;i++){ // out.write(buf[i]); // } // out.close(); // // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // FileInputStream in = new FileInputStream(file); // byte[] bufer=new byte[1024]; // int len = in.read(bufer); // String str = new String(bufer,0,len); // System.out.println(str); byte[] buf=sourse.getBytes(); OutputStream f = new FileOutputStream("file1.txt"); //將字符數組一半的內容寫入文件File.txt for(int i=0;i<buf.length;i+=2){ f.write(buf[i]); } f.close(); OutputStream f1 = new FileOutputStream("file2.txt"); f1.write(buf); f1.close(); OutputStream f2 = new FileOutputStream("file3.txt"); f2.write(buf,buf.length-buf.length/4,buf.length/4); f2.close(); FileInputStream in = new FileInputStream("file1.txt"); FileInputStream in1 = new FileInputStream("file2.txt"); //FileInputStream in2 = new FileInputStream("file3.txt"); byte[] buff = new byte[1024]; int len = in.read(buff); int len1 = in1.read(buff); //int len2 = in2.read(buff); String str = new String(buff,0,len); String str1 = new String(buff,0,len1); //String str2 = new String(buff,0,len2); System.out.println(str); System.out.println(str1); //System.out.println(str2); } }