在用java的io流读写文件时,总是被它的各种流能得很混乱,有40多个类,理清啦,过一段时间又混乱啦,决定整理一下!以防再忘
java输入/输出流体系
1.字节流和字符流
字节流:按字节读取。字符流:按字符读取。
字符流读取方便,字节流功能强大,当不能用字符流时,可以用字节流。
字节流基类:inputstream、outputstream
inputstream方法:
outputstream方法:
字符流基类:reader、writer
reader方法:
writer方法:
2.输入输出流体系
3.转换流
inputstreamreader:字节输入流->字符输入流的转换
outputstreamwriter:字节输出流->字符输出流的转换
例如:字节输入流->字符输入流的转换
字节流使用不方便,而普通的reader读取也不太方便,转换成bufferreader,利用bufferreader的readline(),一次读取一行。
1
2
3
4
5
6
7
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
|
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.文件读写:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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); } } |
总结
以上就是本文关于java输入/输出流体系详解的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出,期待您的宝贵意见。
原文链接:http://www.cnblogs.com/jycboy/p/5301184.html