第一行代码Java-源代码-第11章【课程代码】JavaIO编程_第1页
第一行代码Java-源代码-第11章【课程代码】JavaIO编程_第2页
第一行代码Java-源代码-第11章【课程代码】JavaIO编程_第3页
第一行代码Java-源代码-第11章【课程代码】JavaIO编程_第4页
第一行代码Java-源代码-第11章【课程代码】JavaIO编程_第5页
已阅读5页,还剩23页未读 继续免费阅读

下载本文档

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

文档简介

1、第h章:java io编程11.1文件操作类:file范例11-1:文件基本操作。任意给定一个文件路径,如果文件不存在则创建一个新的文件,如果文件存在则将文件删除。package com.yootk.demo;import java.io.file;public class testdemo public static void main(string args) throws exception file file = new file(hd:test.txth);if (file.exists() file.delete(); else system. println(file.creat

2、enewfile();/此处直接抛岀/设置文件的路径/判断文件是否存在/删除文件ii文件不存在/创建新文件范例笛2 :创建带路径的文件。如果给定的路径为根路径,则文件可以直接利用createnewfile()方法进行创建;如果要创建的文件存在目录,那么将 无法进行创建。所以合理的做法应该是在创建文件前判断父路径(getparent()取得父路径)是否存在,如果不存在则应该 先创建目录(mkdirs()创建多级目录),再创建文件。包含路径的文件创建如图所示。package com.yootk.demo;import java.io.file;public class testdemo publi

3、c static void main(string args) throws exception / 此处直接抛出file file = new file(hd:h + fie.separator + "demo” + fe.separator+ ” hello" + fwe. separator + myootkm + fwe. separator+ htest.txr);/设置文件的路径if (!file.getparentfile().exists() file.getparentfile().mkdirs();system.ot/zprintl n(file.cre

4、atenewfile();/现在父路径不存在/创建父路径/创建新文件范例11-3 :取得文件或目录的信息。package com.yootk.demo;import java.io.file;import java.math.bigdecimal;import java.text.simpledateformat;import java.util.date;public class testdemo public static void main(string args) throws exception / 此处直接拋出 file file = new file(hd:m + fe.sepa

5、rator + ,my.jpgm); / 设置文件的路径 if (file.exists() system.owprintlnf1 是否是文件:"+ (file.isfile();system.ofprintln(”是否是目录:” + (file.isdirectory();文件大小是按照字节单位返回的数字,所以需要将字节单元转换为兆(m)的单元/但是考虑到小数点问题,所以使用bigdecimal处理system.owprintln(”文件大小:h+ (new bigdecimal(double) file.length() / 1024 / 1024).divide(new big

6、decimal(l), 2,bgdecima.round_half_up) + "m");/返回的日期是以long的形式返回,可以利用simpledateformat进行格式化操作system.oprintlnc上次修改时间:11+ new simpledateformat("yyyy-mm-dd hh:mm:ssn).format(new date(file.lastmodified();/判断当前路径是否为目录/ 调用tostring()package com.yootk.demo;import java.io.file;public class testde

7、mo public static void main(stringq args) throws exception / 此处直接抛出file file = new filecc:'1 + fwe.separator if (file.isdirectoryo) file result = file.listfiles();for (int x = 0; x < resultength; x+) syste m. println(resultx);范例11-5:列出指定目录下的所有文件及子目录信息。在每一个目录 中有可能还会存在其他子目录,并且还可能有更深层次的子目录,所 以为了可

8、以列出所有的内容,应该判断每一个给定的路径是否是目 录。如果是目录则应该继续列出,这样的操作最好使用递归的方式完 成。package com.yootk.demo;import java.io.file;public class testdemo public static void main(stringo args) throws exception / 此处直接抛出file file = new file(hc:" + file.separator p加(file);/定义操作路径/列出目录*列岀目录结构,此方法采用递归调用形式* param file要列出目录的路径7publ

9、ic static void print(file file) if (file.isdirectoryo) file result = file.listfiles();if (result != null) for (int x = 0; x < resultength; x+) p別 resultx);system. tjt/zpri ntln (file);/路径为目录/列出子目录/目录可以列出/递归调用/直接输岀完整路径11.2字节流与字符流范例11-6 :自动执行close。操作。字节流与字符流package com.yootk.demo;class net implemen

10、ts autocloseable overridepublic void close() throws exception sys怕m.06/.println(h*网络资源自动关闭,释放资源。h);public void info() throws exception / 假设有异常抛出system.o(/aprintln(w* 欢迎访问:”);public class testdemo public static void main(string args) try (net n = new net()(); catch (exception e) e.printstacktra

11、ce();package com.yootk.demo;import java.io.file;import java.io.fileoutputstream;import java.io.outputstream;public class testdemo public static void main(string args) throws exception / 直接抛出/1.定义要输出文件的路径file file = new file(hd:n + fwe.separator + “demo” + fe.separator+ hmldn.txtn);此时由于目录不存在,所以文件不能输岀

12、,应该首先创建目录if (!file.getparentfile().exists() / 文件目录不存在ii2.应该使用outputstream和其子类进行对象的实例化,此时目录存在,文件还不存在 outputstream output = new fileoutputstream(file);字节输出流需要使用byte类型,罢要将string类对象变为字节数组string str ="更多课程资源请访问:”;byte datao = str.getbytes();/将字符串变为字节数组output.write(data);3 输出内容output.close();/4 .资源操作

13、的最后一定要进行关闭/2应该使用outputstream和其子类进行对象的实例化,此时目录存在,文件还不存在 outputstream output = new fileoutputstream(file,true);范例11-9 :采用单个字节的方式输出(此处可以利用循环操作输出 全部字节数组中的数据)。for (int x= 0 ; x < dataength ; x +) output.write(datax);/ 内容输出范例11-10 :输出部分字节数组内容(设置数组的开始索引和长度)。/内容输出output.write(data, 6, 6);范例11-11:数据读取操作。p

14、ackage com.yootk.demo;import java.io.file;import java.io.fileinputstream;import java.io .in putstream;public class testdemo public static void main(stringq args) throws exception / 直接抛出file file = new filef'd:" + fie.separator + "demo” + fwe.separator+ ,mldn.txtm);/1 .定义要输出文件的路径if (fil

15、e.existso) /需要判断文件是否存在后才可以进行读取/ 2 .使inputstream进行读取in putstream in put = new filel nputstream(file);byte data = new byte 1024;ii 准备出一个 1024的数组int len = input.read(data);ii3 .进行数据读取,将内容保存到字节数组中input.close();/4 .关闭输入流/将读取出来的字节数组数据变为字符串进行输出system.o6/zprintln(" " + new string(data,ojen) + &quo

16、t; m);范例11-12 :采用while循环实现输入流操作。package com.yootk.demo;import java.io.file;import java.io.filelnputstream;import java.io .in putstream;public class testdemo public static void main(stringq args) throws exception / 直接抛出file file = new filefd:" + fe.separator + "demo” + fe.separator+ ,mldn.t

17、xtn);/1 .定义要输出文件的路径if (file.existso) /需要判断文件是否存在后才可以进行读取/ 2使inputstream进行读取inputstream input = new filelnputstream(file);byte data = new byte 1024;/ 准备出一个 1024的数组intfoot = 0;/表示字节数组的操作脚标inttemp = 0;/表示接收每次读取的字节数据/第一部分:(temp = input.read(),表示将read()方法读取的字节内容给temp变量/第二部分:(temp = input.read() != -1 ,判断

18、读取的temp内容是否是 while(temp = input.read() != -1) / 3 .读取数据datafoot + = (byte) temp ;/ 有内容进行保存input.close();/ 4 .关闭输入流system.0zprintln(" " + new string(data,0,foot) + "");范例11-13 :利用do.while实现数据读取。byte data = new byte 1024; int foot = 0 ;int temp = 0 ;dotemp = input.read();if (temp !

19、= -1) /准备出一个1024的数组/表示字节数组的操作脚标/表示接收每次读取的字节数据/读取一个字节/现在是真实的内容datafoot + = (byte) temp ; /保存读取的字节到数组中 while (temp != -1);/如果现在读取的temp的字节数据不是邛,表示还有内容范例11-14 :使用writer类实现内容输出package com.yootk.demo;import java.io.file;import java.io.filewriter;import java.io.writer;public class testdemo public static vo

20、id main(string args) throws exception / 此处直接抛出file file = new filef'd:" + fie.separator + “demo” + file.separator+ "mldn.txt");/1 .定义要输出文件的路径if (!file.getparentfile().exists() /判断目录是否存在file.getparentfile().mkdirs();/创建文件目录writer out = new filewriter(file);/ 2 实例化了 writer类的对象string

21、 str = ”更多课程请访问:”; /定义输出内容 out.write(str);/3 .输出字符串数据out.close();/4 .关闭输出流范例11-15 :使用reader读取数据。package com.yootk.demo;import java.io.file;import java.io.filereader;import java.io.reader;public class testdemo public static void main(stringo args) throws exception / 此处直接抛出file file = new file(hd:h +

22、file.separator + "demo” + fwe.separator+ ,mldn.txth);if (file.exists() reader in = new filereader(file); char data q = new char 1024; int len 二 in.read(data); in.close();定义要输出文件的路径/2 .为reader类对象实例化ii开辟字符数组,接收读取数据/ 3 .进行数据读取4关闭输入流system.ozprintln(new string(dataf 0, len); 范例11-16 :强制清空字符流缓冲区。pac

23、kage com.yootk.demo;import java.io.file;import java.io.filewriter;import java.io.writer;public class testdemo public static void main(string args) throws exception / 此处直接抛出file file = new file(nd:n + file.separator + "demo” + separator+ "mldn.txt”);/1 .定义要输出文件的路径if (!file.getparentfile().e

24、xists() / 判断目录是否存在file.getparentfile().mkdirs();/ 创建文件目录writer out = new filewriter(file);/ 2 .实例化了 writer类的对象string str ="更多课程请访问:" /定义输出内容 out.write(str);/3 .输出字符串数据out.flush();/强制刷新缓冲区11.3转换流范例11-17 :实现输出流转换。package com.yootk.demo;import java.io.file;import java.io.fileoutputstream;impo

25、rt java.io.outputstream;import java.io.outputstreamwriter;import java.io.writer;public class testdemo public static void main(stringo args) throws exception / 此处直接抛出file file = new file(hd:n + fe.separator + "demo” + fe.separator+ "mldn.txt");/1 .定义要输出文件的路径if (!file.getparentfile().ex

26、ists() /判断父路径是否存在file.getparentfile().mkdirs();/创建父路径outputstream output = new fileoutputstream(file);/ 字节流/将outputstream类对象传递给outputstreamwriter类的构造方法,而后向上转型为writerwriter out = new outputstreamwriter(output);out.write(n更多课程请访问:www.yootk.corrt);/ writer类的方法out.flush();out.close();11.4案例:文件复制范例巧:实现文件

27、复制操作。package com.yootk.demo;import java.io.file;import java.io.filelnputstream;import java.io.fileoutputstream;import java.io .in putstream;import java.io.outputstream;public class copydemo public static void main(stringo args) throws exception long start = system.currentt/mem/is(); if (args.length

28、!= 2) system.omprintlnc命令执行错误! ”);/取得复制开始的时间/初始化参数不足2位system .ex/");/程序退岀执行ii如果输入参数正确,应该进行源文件有效性的验证file infile = new file(argso); if (!infile.exists() /第一个为源文件路径/源文件不存在system.o£/.println(h源文件不存在.请确认执行路径。h);system, ex/1);/程序退出/如果此时源文件正确,就需要定义输岀文件,同时要考虑到输岀文件有目录file outfile = new file(args1);

29、if (!outfile.getparentfile().exists() outfile.getparentfile().mkdirs();/输出文件路径不存在/创建目录/实现文件内容的复制,分别定义输岀流与输入流对象inputstream in put = new filelnputstream(infile);outputstream output = new fileoutputstream(outfile);int temp = 0 ;/保存每次读取的数据长度byte data = new byte 1024;/每次读取1024个字节/将每次读取进来的数据保存在字节数组里面,并且返回

30、读取的个数while(temp = input.read(data) != -1) /循环读取数据output.write(data, 0, temp);i/输出数组in put.close();/关闭输入流output.close();/关闭输出流long end = system. currenttimemillis ;/取得操作结束时间system.mprintln("复制所花费的时间:"+ (end -start);11.5字符编码范例11-19 :取得当前系统中的环境属性中的文件package com.yootk.demo;public class testdem

31、o public static void main(stringq args) throws exception sys 怕 m .ge 沪厂opeh/'esq. i ist(system. out);列出全部系统属性范例11-20 :程序出现乱码。package com.yootk.demo;import java.io.file;import java.io.fileoutputstream;import java.io.outputstream;public class testdemo public static void main(string args) throws ex

32、ception file file = new file(hd:h + separator mmldn.txth);outputstream output = new fileoutputstream(file);/强制改变文字的编码,此操作可以通过string类的getbytes()方法实现 output.write(”更多课程请访问:www.yootk.cornm.getbytes(miso8859-1m); output.close();11-6内存流范例11-21 :实现一个小写字母转大写字母的操回豐 作。本程序不使用string类中提供的touppercase()方法,而是利用i0操

33、作,将每一个字节进行大写字母转换; 为了方便地实现字母的转大写操作(避免不必要的字符也被转换)可以借助character包装类的方法。|-转小写字母:public static char tolowercase(char ch);|-转小写字母(利用字母编码转换):public static int tolowercase(int codepoint);|-转大写字母:public static char touppercase(char ch);|-转大写字母(利用字母编码转换):public static int touppercase(int codepoint)opackage com

34、.yootk.demo;import java.io.bytearrayl nputstream;import java.io.bytearrayoutputstream;import java.i on putstream;import java.io.outputstream;public class testdemo public static void main(stringo args) throws exception / 此处直接抛出string str = h & www.mldn.crt; / 要求被转换的字符串/本次将通过内存操作流实现转换,先将数据保存在内存流里面

35、,再从里面取出每一个数据/将所有要读取的数据设置到内存输入流中,本次利用向上转型为inputstream类实例化inputstream in put = new bytearrayl nputstream(str.getbytes();/为了能够将所有的内存流数据取岀,可以使用bytearrayoutputstreamoutputstream output = new bytearrayoutputstream();int temp = 0;/读取每一个字节数据/经过此次循环后,所有的数据都将保存在内存输出流对象中while (temp = input.read() != -1) / 每次读取

36、一个数据/将读取进来的数据转换为大写字母f利用character.touppercase()可以保证只转换字母output.write(character./<7t?perc5se(temp); / 字节输出流/调用tostring()方法/关闭输入流package com.yootk.demo;import java.io.bytearrayoutputstream;import java.io.file;import java.io.fileinputstream;import java.i on putstream;public class testdemo public stat

37、ic void main(string args) throws exception file filea = new filefd:'1 + fwe.separator + ,infoa.txtn);file fileb = new file(nd:h + fe.separator + minfob.txt");inputstream inputa = new filelnputstream(filea);inputstream inputb = new filelnputstream(fileb);bytearrayoutputstream output = new by

38、tearrayoutputstream(); int temp = 0;while (temp = inputa.read() != -1) output.write(temp);while (temp = inputb.read() != -1) output.write(temp);/异常简化处理/文件路径ii文件路径/字节输入流/字节输入流ii内存输出流ii每次读取一个字节/循环读取数据/将数据保存到输出流/循环读取数据/将数据保存到输出流/现在所有的内容都保存在了内存输出流里面,所有的内容变为字节数组取出byte data = output.tobytearray(); output.

39、close();in puta.close();inputb.close();system.o£/zprintln(new strin g(data);ii取出全部数据ii关闭输出流ii关闭输入流/关闭输入流/字节转换为字符串输出11.7打印流范例11-23 :定义打印流工具类package com.yootk.demo;import java.io.file;import java.io.fileoutputstream;import java.i ooexcepti on;import java.io.outputstream;class printutil /实现专门的输出操作

40、功能private outputstream output;ii 输出只能依靠outputstream/*输出流的输出目标要通过构造方法传递* param outputtpublic printutil(outputstream output) this.output = output;public void print(lnt x) / 输出 int型数据this.print(string.valueofl)/调用本类字符串的输出方法public void print(string x) try /采用outputstream类中定义的方法,将字符串转变为字节数组后输出 this.outpu

41、t.write(x.getbytes(); catch (loexception e) e.printstacktrace();public void print(double x) this.print(string. valueof/)public void println(int x) this.println(string. valueoh)public void println(string x) thls.print(x.concat(l,n,');public void println(double x) this.println(string. va!ueo/)publ

42、ic void close() try this.output.close(); catch (loexception e) e.pri ntstacktrace();public class testdemo public static void main(string args) throws exception / 此处直接抛出printutil pu = new printutil(new fileoutputstream(new filefd:11+ fe. separator + hyootk.txtu);pu.print("优拓教育:");pu.println

43、(,');pu.println(1 + 1);pu.println(1.1 + 1.1);pu.close();/输出double型数据/输岀数据后换行输出数据后换行/输出流关闭范例11-24 :使用printstream类实现输出。package com.yootk.demo;import java.io.file;import java.io.fileoutputstream;import java.io.printstream;public class testdemo public static void main(string args) throws exception /

44、 此处直接抛出/实例化printstream类对象,本次利用fileoutputstream类实例化printstream类对象printstream pu = new printstream(new fileoutputstream(new file(hd:m+ fie. separator + ” yootk.txt");pu.print(”优拓教育:h);pu.println(,h);pu.println(1 + 1);pu.println(1.1 + 1.1);pu.close();package com.yootk.demo;import java.io.file;impo

45、rt java.io.fileoutputstream;import java.io.printstream;public class testdemo public static void main(stringo args) throws exception / 此处直接抛出 string name = ”李兴华:int age = 19;double score = 59.95891023456;printstream pu = new printstream(new fileoutputstream(new filef'd:'* + fe. separator + &#

46、39;'yootk.txf');pu.printf(m姓名:%s ,年龄:%d ,成绩:%5.2f name, age, score); pu.close();package com.yootk.demo;public class testdemo public static void main(string args) throws exception string name = ”李兴华:int age = 19;double score = 59.95891023456;string str = string, format'姓名:%s r 年龄:%d f 成绩:

47、%5.2f name, age, score);syste m. oprintln(str);11.8 system类对io的支持package com.yootk.demo; public class testdemo public static void main(string args) throws exception tryi nieger.parse/nt(''a be”);此处一定会发生异常 catch (exception e) system.e/rprintln(e); / 错误输出范例笛2:利用outputstream实现屏幕输出。package com.y

48、ootk.demo;import java.io.outputstream;public class testdemo public static void main(string args) throws exception outputstream out = system .out、 out.write(hh.getbytes();/此处直接抛出异常/ outputstream就为屏幕输出/屏幕输出范例11-29 :消费型函数式接口与方法引用。package com.yootk.demo;import java.util.function.consumer;此处直接拋岀/方法引用/输出p

49、ublic class testdemo public static void main(string args) throws exception consumer<string> con = system.o加:println; con.acceptf1 更多课程请访问:1');范例11-30 :实现键盘的数据输入。package com.yootk.demo;import java.io .in putstream;public class testdemo public static void main(string args) throws exception /

50、 此处直接抛岀/为了方便读者理解,本处将system.in使用inputstream接收,但实际上不需要此操作 inputstream input = system.zrz;/ system.in为 inputstream类实例byte data = new byte1024;/ 开辟空间接收数据system.“/.print("请输入数据:");/信息提示,此处没有换行int len = input.read(data);/读取数据并返回长度system.omprintln(”输入数据为:h + new string(data, 0, len);范例11-31 :改进输入

51、操作设计。package com.yootk.demo; import java.io .in putstream;public class testdemo public static void main(string args) throws exception / 此处直接抛出异常inputstream in put = system in; stringbuffer but = new stringbuffer(); system.omprint("请输入数据:"); int temp = 0;while (temp = input.read() != -1) if

52、 (temp = 'n') break; buf.append(char) temp);/接收输入数据/提示信息/接收每次读取数据长度/判断是否有输入数据/判断是否为回车符/停止接收/保存读取数据/输出内容11.9字符缓冲流:uffered reader范例11-32 :键盘数据输入的标准格式。system.owprintln("输入数据为:"+ buf);package com.yootk.demo;import java.io.bufferedreader;import java.i on putstreamreader;public class testdemo public static void main(string args) throws exception / 此处直接抛出/ system.inmlnputs

温馨提示

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

评论

0/150

提交评论