java中的IO整理-编程开发技术_第1页
java中的IO整理-编程开发技术_第2页
java中的IO整理-编程开发技术_第3页
java中的IO整理-编程开发技术_第4页
java中的IO整理-编程开发技术_第5页
已阅读5页,还剩36页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、java中的io整理-编程开发技术java中的10整理原文出处:rollenholt写在前面:本文章基本覆盖了 jevalo的全部内容,人眩新10没冇涉及,因为 我想和这个分开,以突出那个的重要性,新10哪一篇文章还没有开始写,估计 很快就能和大家见而。照旧,文章依旧以例子为主,因为讲解内容的java书很 多了,我觉的学以致用才是真。代码是写出来的,不是看出来的。最后欢迎人家提岀意见和建议。【案例1】创建一个新文件import java io. *;class hellopublic static void main(string args) file f二new file(d:hello.

2、txt);try f. crcatcncwfilco ;catch (exception e) e. printstacktrace ();【运行结果】:程序运行之后,在d盘下会有一个名字为hello, txt的文件。【案例2】file类的两个常量import java io. *;class hellopublic static void main(string args) system. out. println(file. separator);system, out. prinlln(file. pathseparator);【运行结果】: 此处多说儿彳山有些同学可能认为,我直接在wi

3、ndows k使用进行分割不行吗? 当然是可以的。但是在limix下就不是了。所以,耍想使得我们的代码跨平台, 更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。呵呵、现在我们使用file类中的常量改写上面的代码:import java io. *;class hellopublic static void main (string args) string f订ename二d:+f订e. separator+hello. txt"file f=new file(filename);try f. createnewfile ();catch (exception e) e.

4、 printstacktrace ();你看,没有多写多少吧,呵呵。所以建议使用f订e类中的常量。删除一个文件/*删除一个文件* */import java. io. *;class hellopublic static void main(string args) string filename=,d:z,+filc. scparator+hcllo. txt"file f=new file(filename);if (f. exists () f. delete ();else system, out. printin ("文件不存在);创建一个文件夹 /*创建一个文件

5、夹* */import java. io. *;class hellopublic static void ni3in( str in g args) string filename二"d:"+file separator+,zhelloz,; file f=new file(filename);f. mkdir ();【运行结果】:d盘下多了一个hello文件夹列出指定目录的全部文件(包括隐藏文件):/*使用list列出指定目录的全部文件* */import javaio.*;class hellopublic static void main(string args)

6、string filename=,/d:z,+file separator;file f=ncw file(filename);string str二f. list();for (int i 二 0; i str.length; i+) system, out. prinlln(stri);【运行结果】:$recycle. bin360360downloads360rec360softmoveconf ig. msidadownloadsdriversbackupecl ipsejava web整合开发和项目实战lenovomsocacheprogramprogram filespythonr

7、ecygler. 8f92da15-a229-a4d5-b5ce-5280c8b89c19system volume informationtomcat6 varvod_cache_data新建文件夹(你的运行结果应该和这个不一样的,呵呵)但是使用list返冋的是string数组,。而且列出的不是完整路径,如果想列出 完整路径的话,需要使用listfiles.他返回的是file的数组 列出指定目录的全部文件(包括隐藏文件):/*使用listfiles歹!j出指定目录的全部文件* listfiles输出的是完整路径* */import java. io. *; class hellopublic

8、 static void main(string args) string filename二"d:"+file separator;file f=new file(filename);file str=f. listfiles();for (int i 二 0; i < str. length; i+) system out println(stri);【运行结果】:d:$recycle.bind:360d:360downloadsd:360recd:360softmoved:config.msid:dad:downloadsd:driversbackupd:ecl

9、ipsed:java web整合开发和项目实战d:lcnovod:ms0cached:programd:program filesd:pythond:recygler. 8f92da15-a229-a4d5-b5ce-5280c8b89c19d:system volume informationd:tomcat6d:vard:vod_cache_datad:新建文件夹通过比较可以指定,使用listfiles更加方便、判断一个指定的路径是否为目录/*使用isdirectory判断一个指定的路径是否为目录 * */import java. io. *;class hcllopublic stati

10、c void main(string args) string filename=zzd:/z+file. separator; file f二new file(filename); if (f. isdirectory() system out println("yes");else system, out printin("no");【运行结果】:yes搜索指定目录的全部内容/*列出指定目录的全部内容* */import java io. *;class hellopublic static void main(string args) string

11、 filename二d:+file. separator; file f二new file(filename); print (f);public static void print(file f) if (f!二null)if (f. isdirectory() file filearray=f. listfiles();if (filearray!=null)for (int i 二 0; i < filearray. length; i+) 递归调用 print(filearray i);else system, out. pri ntln(f);【运行结果】:d:tomca t6

12、workc3tal in alocalhostncv clorgeip3chcjspfreinicpagcswc b4welcome_jsp. javad:tomcat6workcatalinalocalhostnevelorgapachejsphelp_005fhome _jsp. classd:tomcat6workcatalinalocalhost'nevelorgapachejsphelp_005fhome _jspjavad:tomcat6workcatalinalocalhostnevelorgapachejsphome_jsp. clas sd:tomcat6workca

13、talinalocalhostnevelorgapachejsphonie_jsp javad:tomcat6workcatalinalocalhost'nevelorgapachejspindex_jsp. classd:tomcat6workcatalinalocalhostnevelorgapachejspindex_jsp. jav ad:tomcat6workcatalinalocalhostnevelorgapachejsplogin_jsp. classd:tomcat6workcatalina'localhost'ncvcl'org'ap

14、achc'jsp'login jsp. jav ad:tomcat6workcatalinalocalhostnevelorgapachejspmodify_005fus er_005finfo_jsp. classd:tomcat6workcatalinalocalhostnevelorgapachejspmodify_005fus er_005finfo jsp.javad:tomcat6workcatali nalocalhos tnevelorgapachejspregi ster_005f notify_jsp. classd:tomcat6workc3talinal

15、ocalhostncvclorgeip3chcjsprcgistcr_005f notify_jsp. javad:tomcat6workcatalinalocalhostnevelorgapachejspsign_005fup_j sp. classd:tomcat6workcatalinalocalhostnevelorgapachejspsign_005fup_j sp. javad:tomcat6workc3talinalocalhostncvclorgeip3chcjsptransit_jsp. c lass【使用randomaccessf订e写入文件】/*使用randomacccs

16、sfilc写入文件* */import java. io. *;class hellopublic static void main(string args) tbrows toexception string filename=,d:z,+filc. scparator+hcllo. txt"file f=new file(filename);randomaccessfile demo二new randomaccessf订e(f, rw); demo. writebytes(asdsad); demo, wri tetnt(12);demo. writcboolcan(true);

17、demo. writecharc a");demo. writefloat (1. 21f); demo. writedouble(12. 123);demo, close();如果你此时打开hello。txt查看的话,会发现那是乱码。字节流【向文件中写入字符吊】/*字节流*向文件中写入字符串* */import java. io.class hellopublic static void main(string args) throws ioexception string filename二d:"+file. separator+hello. 1x1" fil

18、e f=new file(filename);outputstream out =new fileoutputstream(f); string str=,z你好;byte b=str. get bytes ();out. wri te (b);out. closeo ;查看hello, txt会看到“你好”当然也可以一个字节一个字节的写。/*字节流*向文件中一个字节一个字节的写入字符串* */import java. io. *;class hellopublic static void main(string args) throws ioexception string filename

19、=d:+file. separator+hello. txt" file f=new file(filename);outputstream out =new fileoutputstream(f);string str二你好;bytc b=str. gctbytcs ();for (int i = 0; i < b.length; i+) out. write(bi);out. closeo ;结果还是:“你好” 向文件小追加新内容:/*字节流*向文件中追加新内容:* */import java. io. *;class hcllopublic static void mai

20、n(string args) throws loexception string filename=z'd:z,+file. separator+/zhello. txt" file f二new file(filename);outputstream out 二new fi1eoutputstream(f, true);string str=z,rollcrt;/string str二"rnrollert;可以换行 byte b=str. getbytes ();for (int i 二 0; i < b.1ength; i+) out. write(bi);

21、out. close ();【运行结果】:你好rollon【读取文件内容】/*字节流*读文件内容* */import javaio.*;class hellopublic static void main( str ing args) throws toexception string filename=,/d:z,+file separator+hello. txt" file f=ncw file(filename);inputstream in=new filelnputstreankf);byte b=new byte1024;in. read(b);in. close ()

22、;system out printin(new string(b);【运行结果】你好rollonrollen_但是这个例子读取出来会有大量的空格,我们可以利用in.read(b);的返冋值来 设计程序。如下:/*字节流*读文件内容* */import java. io. *;class hellopublic static void ni3in( str in g args) throws ioexccption string filename二"d:"+file separator+,zhello. txt"file f=new file(filename);i

23、nputstream in二new filelnputstream(f); byte b=new byte1024;int lcn二in. rcad(b);in. close ();system, out. printin (,z读入长度为:+len); system, out. print in (new str in g(b, 0, len);【运行结果】:读入长度为:18你好rollenrollen读者观察上面的例了可以看出,我们预先中请了一个指定大小的空间,但是有时 候这个空间可能太小,冇时候可能太大,我们需要准确的大小,这样节省空间, 那么我们可以这样干:/*字节流*读文件内容,节省

24、空间* */import java. io. *;class hellopublic static void main(string args) throws toexception string filename=,d:z,+filc. scparator+hcllo. txt"file f二new file(filename);inputstream in二new filelnputstream(f); byte b=new byte(int)f. length();in. read(b); system, out. printin(文件长度为:z,+f. length(); i

25、n. closeo ;system out println(new string(b);文件长度为:18你好rollonrollen将上面的例了改为一个一个读:/*字节流*读文件内容,节省空间* */import java. io. *;class hellopublic static void main(string args) throws toexception string filename=,d:z,+filc. scparator+hcllo. txt"file f=new file(filename); inputstream in=new fi1elnputstrea

26、m(f); byte b 二 new byte (in t) f. le ngth(); for (int i 二 0; i < b.length; i+) bi二(byte) in. read();in. close (); system, out. print in (new str in g(b);输出的结果和上而的一样。细心的读者可能会发现,上面的儿个例了都是在知道文件的内容多大,然后才展 开的,有时候我们不知道文件有多大,这种情况下,我们需耍判断是否独到文件 的末尾。/*字节流*读文件* */import java. io. *;class hellopublic static

27、 void main(string args) tbrows toexception string filename=,d:z,+filc. scparator+hcllo. txt" file f=new file(filename);inputstream in二new filelnputstream(f); byte b二new byte1024;int count 二0;int tcmp=0;while(temp=in. reado) ! = (-l) bcount+二(byte)temp;in. close(); system, out. printin(new strin

28、g(b);【运行结果】你好rol 1 enrollcn_提醒一下,当独到文件末尾的时候会返回-1 正常情况下是不会返回-1的字符流【向文件中写入数据】现在我们使用字符流/*字符流*写入数据* */import java. io. *;class hellopublic static void main(string args) throws ioexception string f i 1 ename=/zd: /z+fi 1 e. separator+/zhello. txt; file f=new file(filename);writer out 二new filewritcr(f);s

29、tring str二hello"out write (str); out. close ();当你打开hclloo txt的时候,会看到hello其实这个例子上z前的例子没什么区别,只是你可以直接输入字符串,而不需要 你将字符串转化为字节数组。当你如果想问文件屮追加内容的吋候,可以使用将上面的声明out的哪一行换 为:writer out =new?filcwriter(f, true);这样,当你运行程序的时候,会发现文件内容变为:hellohello |果想在文件中换行的话,需要使用“rn”比如将 str 变为 string str二” rnhello” ;这样文件追加的str的

30、内容就会换行了。从文件中读内容:/*字符流*从文件中读出内容* */import java, io.*;class hellopublic static void main(string args) throws loexception string f订ename二d:+f订e. separator+hello. txt; file f二new file(filename);cheir ch=new cheir 100;reader rcad=new filcrcadcr(f);int count=read. read(ch);read, close ();system, out. prin

31、tin(,z读入的长度为+count); system. out. println(内容为"+new string(ch, 0, count);【运行结果】:读入的长度为:17 内容为 hellohellohello当然最好采用循环读取的方式,因为我们冇时候不知道文件到底冇多大。/*字符流*从文件中读出内容* */import java io. *;class hellopublic static void main(string args) throws loexception string f订ename二d:+f订e. separator+,zhello. txt"f

32、ile f二new file(filename);chart ch=new char100;reader rcad=ncw filcreadcr(f);int temp=0;int count二0;while(temp=read. read() ! = (-l) ch count+ = (char) temp;read, close ();sys tem. out. printing 内容为"+new str in g(ch, 0, count);运行结果:内容为 hcllohcllohello关于字节流和字符流的区别实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操

33、作 的,但是字符流在操作的?时候卜后是会用到缓冲区的,是通过缓冲区來操作文 件的。读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释 掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但 是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。使用字节流好还是字符流好呢?答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存 的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节 流使用广泛。文件的复制其实dos下就冇一个文件复制功能,比如我们想把d盘下而的h e 1 1 ot x t文件复制到d盘下面的rollen

34、. txt文件中,那么我们就可以使用下面的命 令:copy d:hello. txt d:rollen. txt运行之后你会在d盘中看见hello, txt.,并口两个文件的内容是一样的,(这 是屁话)下面我们使用程序來复制文件吧。基本思路还是从一个文件中读入内容,边读边写入另一个文件,就是这么简单。、首先编写下而的代码:/*文件的复制* */import java io. *;class hellopublic static void main(string args) throws ioexception if (args, length!=2) system, out. printlnc

35、'命令行参数输入有误,请检查"); systcm. exit ;file filel=new file (args0);file f订e2=new f订e(argsl);if (!filel. exists() system, out. println(/z被复制的文件不存在"); system. exit 仃);inputstream input二new filelnputstream(filel);outputstream output二new fileoutputstream(file2); if(input!=null)&&(output!=

36、null) int temp二0; while (temp= in put. read () !二(-1) output write(temp);input, close (); output, close ();然后在命令行下面javac hello, javajava hello d:hello. txt d:rollen. txt现在你就会在d盘看到rolleno txt 了,outputstreramwriter?d inputstreamreader 类整个10类屮除了字节流和字符流述包括字节和字符转换流。outputstreramwriter将输出的字符流转化为字节流inputst

37、reamreader将输入的字节流转换为字符流但是不管如何操作,最后都是以字节的形式保存在文件中的。将字节输出流转化为字符输出流/*将字节输出流转化为字符输出流* */import java, io.*;class hellopublic static void main(string args) throws loexception string filename= /zd:z/+file. separator+/zhello. txt/z; file file二new file(filename);wri ter out 二 new outputst reamwr it er (new f

38、ileo utputst ream (file); out. write ("hello");out. close ();运行结果:文件屮内容为:hello 将字节输入流变为字符输入流/*将字节输入流变为字符输入流* */import java. io. *;class hellopublic static void main(string args) throws ioexception string filename= d:+f订e. separator+hello. txt;file file二new file(filename);reader rcad=ncw in

39、putstrcamrcadcr(new filclnputstrcam(filc); char b二new char100;int len=read. read(b);system, out. print in (new str in g(b, 0, len); read, close();【运行结果】:hello前面列举的输岀输入都是以文件进行的,现在我们以内容为输出输入目的地,使 用内存操作流by tcarray inputstrcam?主要将内容写入内容bytearrayoutputstream?主要将内容从内存输出使用内存操作流将一个大写字母转化为小写字母/*使用内存操作流将一个大写字

40、母转化为小写字母* */import java. io. *;class hellopublic static void m8in(string args) throws ioexception string str二rollenholt;bytcarreiy in putstrcam in put 二 newbytearraylnputstream(str getbytes ();bytearrayoutputstrearn output二new bytearrayoutputstream(); int temp二0;while(temp二input, read() !二-1) char c

41、h= (char)temp;output write(character. tolowercase(ch);string outstr二output. tostring(); in put. close ();output, close ();system, out. println(outstr);【运行结果】:rollenholt内容操作流一般使用來生成一些临时信息采用的,这样可以避免删除的麻烦。 管道流管道流主要可以进行两个线程z间的通信。pipedoutputstream?管道输ill 流pipedtnputstream?管道输入流验证管道流/*验证管道流* */import java

42、. io. *;/*消息发送类* */class send implements runnable private pipedoutputstream out=null;public send() out=new pipedoutputstream();public pipedoutputstream getout()return this.out;ijpublic void run() string message二hello , rollert;try out. wri te(message. etbytes ();catch (exception c) e. printstacktrac

43、e (); try out. close ();catch (exception e) c. printstacktracco ; /*接受消息类* */class recive implements runnableprivate piped!nputstream input二null;public recive()this. input=new pipedlnputstream(); public pipedlnputstream getlnput() return this. input;public void run() byte b=new byte1000;int len二0;tr

44、y len二this. input, read(b);catch (exception c) e. printstacktrace (); try in put. close ();catch (exception e) e. printstacktrace (); _system, out. printin(,z接受的内容为 +(new string(b, 0, len); /*测试类* */class hellopubl ic static void main(string args) tbrows toexception send send二new send ();recive reci

45、ve=new recive();try 管道连接send. getout () connect (recive. getlnput ();catch (exception e) e. printstacktrace ();new thread (scnd), start();new thread(recive). start();【运行结果】:接受的内容为?hcllo , rollon打印流/*使用printstream进行输岀* */import java. io.class hello public static void main(string args) throws toexcept

46、ion printstream print 二 new printstream(new fi1eoutputstream(new f 订 c(d:+ file, separator + "hello.txt");print, println(true);print, printin(rollen); print. close();【运行结果】:truerollen当然也可以格式化输出/*使用printstream进行输出*并进行格式化* */import java, io.*;class hello public static void main(string args)

47、throws loexception printstream print 二 new printstream(new fi1eoutputstream(new f 订 e(d:+ file, separator + "hello.txt");string name=,zrollcrt;int age=20;print, printf (,z姓名:%s.年龄:%, age); print, close ();【运行结果】:姓名:rollen. ?年龄:20.使用outputstream向屏幕上输出内容/*使用outputstrcam向屏幕上输出内容* */impo

48、rt java. io. *; class hello public static void main(string args) throws ioexception outputstrcam out二system, out;try out. write (hello getbytes ();catch (exception e) e. printstacktrace ();try out. close ();catch (exception e) e. printstacktrace();【运行结果】:hello输入输出重定向import java. io. file;import java

49、. io.filenotfoundexception; import java. io.fileoutputstream;import java. io. printstream;/* 为 system, out. printin ()重定向输出* */public class systemdeino public static void main(string args) /此刻直接输出到屏幕system, out. println("hello");file file = new file(d:" + file.separator + "hello.

50、txt");system. setout(new printstream(newfileoutputstream(file);catch (filenotfoundexccption c)e. printstacktrace ();system, out. printin(,z这些内容在文件中才能看到哦! );【运行结果】:eclipse的控制台输出的是hello。然后当我们查看d盘下面的hello, txt文件 的时候,会在里面看到:这些内容在文件中才能看到哦!import java. io. file;import java. io. fi1emotfoundexception;

51、import java. io. filcoutputstream;import java. io. printstream;* system, err重定向这个例子也提示我们口j以使用这种方法保存错误信息* */public class systemerr public static void main(string args)file file 二 new f订e(d: + file, separator + "hello.txt); system, err. printin(这些在控制台输出); try system. seterr(new printstream(newfil

52、eoutputstream(file);catch(filenotfoundexception e)e. printstacktrace();system, err. printlnc这些在文件中才能看到哦! “);【运行结果】:你会在eclipse的控制台看到红色的输出:“这些在控制台输出”,然后在d 盘卜面的hello, txt中会看到:这些在文件中才能看到哦!import java io.file;import java. io. filelnputstream;import java io. f订enotfoundexception;import java io. toexceptio

53、n;/* system, in 重定向* */public class systemin public static void main(string args) file file = new filec'd:" + file .separator + "hell o. txt"); if (!file. existso) return;else trysystem setln(new filelnputstream(file);catch(f订enotfoundexception e)e. printstacktrace ();byte bytes 二

54、 new byte1024;int len = 0;try len = system, in. read (bytes);catch (loexception e) e. pri ntstacktrace ();system, out. println(,z读入的内容为:"+ new string(bytes, 0, len);【运行结果】: 前提是我的d盘下面的hello, txt中的内容是:“这些文件中的内容哦!”,然 后运行程序,输岀的结果为:读入的内容为:这些文件屮的内容哦!bufferedreader 的小例子 注意:?bufferedreqder只能接受字符流的缓冲区,因为每一个中文需要占据两 个字节,所以需要将system, in这个字节输

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论