工作小驛

          Ninja!

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            103 Posts :: 0 Stories :: 36 Comments :: 0 Trackbacks
          我是一個java初學者碰到一些小問題,希望前輩們給我解答一下,謝謝!
          原題目:
          編寫應用程序,利用緩沖輸入流BufferedInputStream 從鍵盤輸入字符串,當輸入的字符串為“exit”時結束輸入,將輸入的所有字符串存放到 my file.txt中。
          編寫應用程序,讀出“my file.txt”的內容,并將讀出的內容輸出到屏幕上,讀文件結束后,顯示“Finished reading,programe ended.”.
          代碼:
          import java.io.*;
          public class Ex3
          {
          public static void main(String[]args)throws Exception
          {
          BufferedInputStream bis=new BufferedInputStream(System.in);
          FileWriter fw=new FileWriter("my file.txt");
          while(true)
          {
          byte[]b=new byte[200];
          int len=bis.read(b);
          String str=new String(b,0,len-2);
          if(str.equals("exit"))
          {
          System.exit(0);
          }
          fw.write(str);
          fw.flush();
          }
          }
          }
          上面的代碼中為什么String str=new String(b,0,len-2);這個方法的參數最后一個要用
          len-2?嘗試過len或者len-1,結果會將exit也寫入文件,len-1還有回車操作符,不明白。
          試寫的代碼:
          import java.io.*;
          public class Ex4
          {
          public static void main(String[]args)throws Exception
          {
          FileReader fr=new FileReader("my file.txt");
          FileOutputStream fos=new FileOutputStream("my file.txt");
          int c;
          byte b[]=new byte[200];
          int len=fr.read();
          while((c=fr.read())!=-1)
          {

          fos.write(b);
          }
          System.out.print("Finished reading,programe ended.");
          fr.close();
          fos.close();

          }
          }
          思路是否正確,這道題應該怎么寫?
          posted on 2007-09-24 08:18 王君 閱讀(401) 評論(1)  編輯  收藏 所屬分類: J2SE

          Feedback

          # re: 關于輸入輸出流的一個問題 2007-09-27 19:29 千里冰封
          你用BufferedReader就更方便了  回復  更多評論
            

          主站蜘蛛池模板: 张掖市| 三门县| 濮阳县| 大余县| 民乐县| 集安市| 五常市| 罗甸县| 八宿县| 云霄县| 峡江县| 晋城| 聂荣县| 南召县| 通榆县| 阆中市| 兴安盟| 腾冲县| 灵宝市| 咸阳市| 讷河市| 修水县| 炉霍县| 苗栗市| 古交市| 阜宁县| 景德镇市| 博客| 黔西| 沈阳市| 外汇| 涿州市| 滦南县| 阿勒泰市| 高淳县| 肥乡县| 江华| 日土县| 天柱县| 祁阳县| 沭阳县|