在用java的io流讀寫文件時,總是被它的各種流能得很混亂,有40多個類,理清啦,過一段時間又混亂啦,決定整理一下!以防再忘
Java輸入/輸出流體系
1.字節流和字符流
字節流:按字節讀取。字符流:按字符讀取。
字符流讀取方便,字節流功能強大,當不能用字符流時,可以用字節流。
字節流基類:InputStream、OutputStream
InputStream方法:
OutputStream方法:
字符流基類:Reader、Writer
Reader方法:
Writer方法:
2.輸入輸出流體系
3.轉換流
InputStreamReader:字節輸入流->字符輸入流的轉換
OutputStreamWriter:字節輸出流->字符輸出流的轉換
例如:字節輸入流->字符輸入流的轉換
字節流使用不方便,而普通的Reader讀取也不太方便,轉換成BufferReader,利用BufferReader的readLine(),一次讀取一行。
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String result = ""; String line = ""; while((line = reader.readLine())!= null){ result = result+ line; } System.out.println(result);
InputStream to String:
private static String changeInputeStream(InputStream inputStream,String encode) { //通常叫做內存流,寫在內存中的 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if(inputStream != null){ try { while((len = inputStream.read(data))!=-1){ outputStream.write(data, 0, len); } //result是在服務器端設置的doPost函數中的 result = new String(outputStream.toByteArray(),encode); outputStream.flush(); outputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }
InputStream->StringBuffer:
StringBuffer buffer = new StringBuffer(); InputStreamReader reader =new InputStreamReader(request.getInputStream(),"utf-8"); char[] requestchar = new char[5]; if(reader != null){ System.out.println("默認編碼:"+reader.getEncoding());//默認編碼:UTF8 } //buffer reader.readLine() while((temp = reader.read(requestchar))!=-1){ buffer.append(requestchar, 0, temp); System.out.println(buffer.toString()); } String result = buffer.toString();
4.文件讀寫:
class Kaoshi {public static void main(String[] args){ Scanner in=new Scanner(System.in); int score=0; //分數; StringBuffer answer=new StringBuffer();//存放用戶答案,動態字符串; String result="ACDD"; //正確答案; try{ FileReader file=new FileReader("Test.txt"); //打開文件; BufferedReader intw=new BufferedReader(file); //緩沖流,按行讀; String s=null; while((s=intw.readLine())!=null){ //判斷不為空; if(!s.startsWith("*")){ System.out.println(s); } else{ System.out.println("請輸入正確答案:"); String str=in.next(); char c= str.charAt(0);//收集答案; answer.append(c); } } }catch(IOException e){ e.printStackTrace(); } for(int i=0;i<result.length();i++){ if(result.charAt(i)==answer.charAt(i)|| result.charAt(i)==answer.charAt(i)-32){ score+=25; } } System.out.println(score); } }