我是一個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();
}
}
思路是否正確,這道題應該怎么寫?