java文件流的操做

//讀取二進制文件
 

public static void ReadBinaryFile()
 {
  System.out.println("請輸入你要讀的文件路徑:");
  Scanner in = new Scanner(System.in);
     String path = in.next();
  try {
   FileInputStream inputFile = new FileInputStream(path);
   DataInputStream input = new DataInputStream(inputFile);
   FileOutputStream outFile = new FileOutputStream("d:\\first.class");
   DataOutputStream output = new DataOutputStream(outFile);
   int size = input.available();
   byte[] me = new byte[size];
   input.read(me);
   output.write(me);
   output.close();
   outFile.close();
   input.close();
   inputFile.close();
   System.out.println("文件複製成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public static void BufferWriter()
 {
//  使用緩衝區存數據 此種效率高
  System.out.println("請輸入你要寫入的文件路徑:");
  Scanner in = new Scanner(System.in);
     String path = in.next();
     try {
   FileWriter fw = new FileWriter(path);
   BufferedWriter bw = new BufferedWriter(fw);
   System.out.println("請輸入你要寫進文件的內容");
   //bw.write(in.next());
   //bw.newLine();
   bw.append(in.next());//添加數據
   bw.close();
   fw.close();
   System.out.println("文件寫入成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public static void BufferRead()
 {
  //使用緩衝區存數據 此種效率高
  System.out.println("請輸入你要讀的文件路徑:");
  Scanner in = new Scanner(System.in);
     String path = in.next();
  try {
   FileReader fr = new FileReader(path);
   BufferedReader br = new BufferedReader(fr);
   String str = null;
    while((str=br.readLine())!=null)
    {
     System.out.println(str);
    }
   br.close();
   fr.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  };
 }
 
 public void WriteFile()
 {
  System.out.println("請輸入你要寫入的文件路徑:");
  Scanner in = new Scanner(System.in);
     String path = in.next();
     try {
      //寫入流
   OutputStream file = new FileOutputStream(path);
   System.out.println("請輸入要寫入地文件內容:");
   String str = in.next();
   byte[] words = str.getBytes();
   file.write(words);
   file.close();
   System.out.println("寫入成功");
   } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public static void ReadFile()
 {
  System.out.println("請輸入你要讀取的文件路徑:");
  Scanner in = new Scanner(System.in);
     String path = in.next();
     try {
//      讀入流
   InputStream file = new FileInputStream(path);
   int size;
    size = file.available();
   System.out.println("文件可讀取的最大數:"+size);
   byte[] text = new byte[size];
    file.read(text,0,size);
    String s = new String(text);
    System.out.println(s);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }app

相關文章
相關標籤/搜索