1. 程式人生 > 程式設計 >JAVA檔案讀寫例題實現過程解析

JAVA檔案讀寫例題實現過程解析

練習

有這樣的一個words陣列,陣列中每個字串的格式為“詞性:單詞”

String[] words = {"verb:eat","verb:drink","verb:sleep","verb:play","noun:rice","noun:meat","noun:hand","noun:hair"};

根據單詞性質動詞verb全部存入verb.txt檔案中

根據單詞性質名詞noun全部存入noun.txt檔案中

package readandwrite;
/*1.有這樣的一個words陣列,陣列中每個字串的格式為“詞性:單詞”
    String[] words = {"verb:eat","noun:hair"};
    根據單詞性質動詞verb全部存入verb.txt檔案中
    根據單詞性質名詞noun全部存入noun.txt檔案中

*/

import java.io.*;


public class FileReadAndWrite {
  public static void main(String args[]) throws IOException {
    //WORDS陣列
    String[] words = {"verb:eat","noun:hair"};
    FileOutputStream outFile1 = new FileOutputStream("verb.txt");
    FileOutputStream outFile2 = new FileOutputStream("noun.txt");
    OutputStream out1 = new BufferedOutputStream(outFile1);
    OutputStream out2 = new BufferedOutputStream(outFile2);

    for(int i=0;i<words.length;i++){
      if(words[i].startsWith("verb")){
        byte[] bytes1 = words[i].getBytes();
        out1.write(bytes1);
      }
      if(words[i].startsWith("noun")){
        byte[] bytes2 = words[i].getBytes();
        out2.write(bytes2);
      }
    }
    out1.close();
    out2.close();
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。