1 / 39

第十章 Java 的文件和流 10.1 流类库简介 10.2 基本流 10.3 数据流 10.4 文件类 File 10.5 文件输入输出 10.6 随机访问文件

第十章 Java 的文件和流 10.1 流类库简介 10.2 基本流 10.3 数据流 10.4 文件类 File 10.5 文件输入输出 10.6 随机访问文件. 第十章 Java 的文件和流 10.1 流类库简介 1. 流的概念 在程序中提供一种将数据源连接到应用程序的方法 . Java 的 I/O 机制都是基于数据流的 , 数据流表示字符或者字节数据的流动序列 . 输入流 : 应用程序到外部 示意图见 P 199 输出流 : 外部到应用程序 示意图见 P 199

emmly
Download Presentation

第十章 Java 的文件和流 10.1 流类库简介 10.2 基本流 10.3 数据流 10.4 文件类 File 10.5 文件输入输出 10.6 随机访问文件

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第十章 Java的文件和流 10.1 流类库简介 10.2 基本流 10.3 数据流 10.4 文件类File 10.5 文件输入输出 10.6 随机访问文件

  2. 第十章 Java的文件和流 10.1 流类库简介 1.流的概念 在程序中提供一种将数据源连接到应用程序的方法. Java的I/O机制都是基于数据流的,数据流表示字符或者字节数据的流动序列. 输入流:应用程序到外部 示意图见P199 输出流:外部到应用程序 示意图见P199 流:A.字节流 抽象类InputStream 、OutputStream B.字符流 抽象类Reader 、Writer

  3. 2.Java的I/O库 字节流:用于处理字节的输入和输出. InputStream和OutputStream的类继承结构图 如图P200 InputStream和OutputStream的常用子类 如表P200 InputStream和OutputStream的主要方法 如书P201 字符流: 用于处理字符的输入和输出,采用Unicode编码 Reader和Writer的类继承结构图 如图P202 Reader和Writer的常用子类 如表P202 Reader和Writer的主要方法 read() write() 其余类似字节流

  4. 10.2 基本流 完成基本的输入和输出操作. 标准I/O: 标准输入文件是键盘,标准输出文件是你的终端屏幕。标准错误输出文件也指向屏幕,如果有必要,它也可以指向另一个文件以便和正常输出区分。系统类Java通过系统类达到访问标准输入输出的功能。 标准流对象: 标准输入流System.in 标准输出流System.out 标准出错流System.err

  5. 1) 基本的键盘输入 A.System.in作为InputStream类的一个实例来实现标准输入。 可以使用read()和skip(long n)两个成员函数。read()让你从输入中读一个字节,skip(long n)让你在输入中跳过n个字节。 例子1: P204 10-1 B.使用流类接受键盘的输入 例如使用InputStreamReader 、BufferReader类 例子2: P204 10-2 C.非标准输入输出方法 Console类(略)

  6. import java.io.*; //例子3 class myIODemo1{ public static void main(String args[]) throws IOException{ int b; int count=0; while((b=System.in.read())!=36) { //36为$的ASCII值 count++; System.out.print((char) b); } System.out.println(); // 增加blankline System.err.println(“ counted "+count+" totalbytes."); } }

  7. 2) 基本的键盘输出 A.System.out作为PrintStream来实现标准输出。 可以使用print()和println()两个成员函数。这两个函数支持Java的任意基本类型作为参数。 例子4: P205 10-4 B. 控制显示格式 java.text包的NumberFormat类 控制格式化字符 NumberFormat.getNumberIntance() 数值 NumberFormat.getCurrencyIntance() 货币 NumberFormat.getPercentIntance() 百分数 每种方法都返回一个NumberFormat对象,调用该对象的format方法来获得一个包含格式化数的字符串。 例子5: P206 10-5

  8. C. 用户自定义的格式 java.text包的DecimalFormat类 (略)

  9. 10.3 数据流 1.DataInputStream类 实现了DataInput接口 可以直接读任意一种变量类型,如浮点数,整数和字符等。 (1)打开和关闭DataInputStream DataInputStream myDataStream; myDataStream=new DataInputStream(InputStream in ); myDataStream.close(); myFileStream.close();

  10. (2)DataInputStream的主要方法: P210 byte readByte() int readUnsignedByte() short readShort() int readUnsighedShort() char readChar() int readInt() long readLong() float readFloat() double readDouble() String readLine()

  11. 2 DataOutputStream类 实现了DataOutput接口 可以直接写任意一种变量类型,如浮点数,整数和字符等。 (1)打开和关闭DataOutputStream DataOutputStream myDataStream; // FileOutputStream myFileStream; // myFileStream=new FileOnputStream("/usr/db/stock.log"); //myDataStream=new DataOutputStream(myFileStream); myDataStream=new DataOutputStream(OutputStream out); myDataStream.close(); //myFileStream.close(); (2)DataOutputStream的主要方法: P210

  12. void writeBoolean(boolean v) void writeByte(int v) void writeShort(int v) void writeChar(int v) void writeInt(int v) void writeFloat(float v) void writeDouble(double v) void writeBytes(String s) void writeChars(String s)

  13. 10.4 文件类File 1. 创建文件File对象 File myFile; (1)myFile=newFile(" etc/motd ");//根据路径创建 (2)myFile=newFile(" /etc ", " motd "); //根据指定目录和文件创建 (3)File myDir=new File("/etc"); myFile=new File(myDir, " motd "); //根据目录对象创建 2.方法 例子6:

  14. import java.io.*; class fileInfo{ public static void main(String args[]) throws IOException{ File fileToCheck; if(args.length>0){ for(int i=0;i<args.length;i++){ fileToCheck=new File(args[i]); info(fileToCheck); } }else{ System.out.println("No file given."); } }

  15. public static void info(File f) throws IOException{ System.out.println("Name: "+f.getName()); System.out.println("Path: "+f.getPath()); if(f.exists()){ System.out.println("File exists."); System.out.print((f.canRead()?"and is Readable ":" ")); System.out.print((f.canWrite()?"and is Writeable ":" ")); System.out.println("."); System.out.println("File is "+f.lenght()+" bytes."); }else{ System.out.println("File does not exist."); } } }

  16. 10.5 文件输入输出 文本文件 Reader和Writer InputStream和OutputStream 二进制文件 InputStream和OutputStream

  17. 1.FileInputStream FileInputStream典型地表示一种顺序访问的文本文件。通过使用FileInputStream你可以访问文件的一个字节、几个字节或整个文件。 (实现文件字节流的输入) (1)构造方法 FileInputStream myFileStream; myFileStream=new FileInputStream("文件名"); (2) read()方法 int read()//读一个字节 int read(byte b[])//读字节数组 int read(byte b[],int offset,int len) //读一定长度的字节数组 (3) close()方法 关闭FileInputStream

  18. 2 .FileOutputStream类 FileOutputStream用于向一个文本文件写数据。象输入文件一样,你得先打开这个文件后才能写这个文件。 (1)构造方法 FileOutputStream myFileStream; myFileStream = new FileOutputStream("文件名"); (2)write()方法 void write(int b);// 写入一个字节 void write(byte b[]);//写入一个字节数组 void write(byte b[],int offset,int length);//写入一定长度的字节数组 (3) close()方法 关闭FileOutputStream

  19. 例子7: 让用户输入一组姓名和电话号码。每一个姓名和号码将加在文件里。 用户通过点“Done"按钮来告诉系统整个列表已输入完毕。 一旦用户输入完整个列表,程序将创建一个输出文件并显示或打印出来。 import java.io.*; public class Phones{ static FileOutputStream fos; public static final int lineLength=81; public static void main(String args[]) throws IOException{ byte[] phone=new byte[lineLength]; byte[] name=new byte[lineLength]; int i; fos=new FileOutputStream("phonenumbers");

  20. while(true) { System.err.println("Enter a name(enter 'done' to quit)"); readLine(name); if("done".equalsIgnoreCase(new String(name,0,0,4))){ break; } System.err.println("Enter the phone number"); readLine(phone); for(i=0;phone[i]!=0;i++) { fos.write(phone[i]); } fos.write(','); for(i=0;name[i]!=0;i++) { fos.write(name[i]); } fos.write('\n'); } fos.close(); } //end of main

  21. private static void readLine(byte line[]) throws IOException{ int i=0,b=0; while((i<lineLength-1)&&((b=System.in.read())!='\n')){ line[i++]=(byte)b; } line[i]=(byte)0; } }

  22. 3. 二进制文件读写 A.二进制文件的写 通过FileOutputStream类和DataOutputStream类来实现的. 格式: FileOutputStream myFileStream= new FileOutputStream("文件名"); DataOutputStream myDataStream=new DataOutputStream(myFileStream); 或: DataOutputStream myDataStream = new DataOutputStream (new FileOutputStream("文件名")); 在用类似如下的代码向文件中写入数据: myDataStream.writeInt(……); myDataStream.writeChar(……); 例子8: P213 10-6

  23. B.二进制文件的读 通过FileInputStream类和DataInputStream类来实现的. 格式: FileInputStream myFileStream= new FileInputStream("文件名"); DataInputStream myDataStream=new DataInputStream(myFileStream); 或: DataInputStream myDataStream = new DataInputStream (new FileInputStream("文件名")); 在用类似如下的代码向文件中写入数据: myDataStream.readInt(……); myDataStream.readChar(……); 例子9: P214 10-7 例子10: P214 10-8 (复制文件)

  24. 4. 文本文件读写 二进制文件的读写速度快,效率高.文本文件的识别性好. A.文本文件的写 1) 通过FileOutputStream类和PrintStream类来实现的. 格式: FileOutputStream myFileStream= new FileOutputStream("文件名"); PrintStream myPStream=new PrintStream(myFileStream); 或: PrintStream myPStream = new PrintStream (new FileOutputStream("文件名") ); 在用如下的代码向文件中写入数据: myPStream.println(……); 最后myPStream.close(); 例子11: P216 10-9

  25. 2) 通过FileWriter类和PrintWriter类来实现的. 格式: FileWriter myFile= new FileWriter("文件名"); PrintWriter myPStream=new PrintWriter (myFile); 或: PrintWriter myPStream = new PrintWriter (new FileWriter ("文件名") ); 在用如下的代码向文件中写入数据: myPStream.print(……); 或 myPStream.println(……); 最后myPStream.close(); myFile.close(); 例子12: P217 10-10

  26. B.文本文件的读 1)通过FileInputStream类和DataInputStream类来实现的. 格式: FileInputStream myFileStream= new FileInputStream("文件名"); DataInputStream myDataStream=new DataInputStream(myFileStream); 或: DataInputStream myDataStream = new DataInputStream (new FileInputStream("文件名")); 在用如下的代码向文件中写入数据: myDataStream.readLine(……); 最后myDataStream.close(); myFileStream.close(); 例子13: P217 10-11

  27. 2)通过FileReader类和BufferedReader类来实现的. 格式: FileReader myFileStream = new FileReader ("文件名"); BufferedReader myData = new BufferedReader(myFileStream); 或: BufferedReader myData = new BufferedReader (new FileReader ("文件名")); 在用如下的代码向文件中写入数据: myData.readLine(……); 最后myData.close(); myFileStream.close(); 例子14: P218 10-12 例子15: P219 10-13 (自学)

  28. 例子16: import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class myBooklist2 extends Frame implements ActionListener { Vector savestring = new Vector(); Frame f; TextField addbook; TextArea listbook; Label l1,l2; Button bopen,bsave,badd,bexit;

  29. public static void main(String args[]) { myBooklist mybl = new myBooklist(); mybl.init(); } public void init() { f=new Frame(" book list "); f.setLayout(new FlowLayout()); Label l1= new Label("add your book here",Label.RIGHT); Label l2= new Label("Book list"); addbook = new TextField("",30); listbook = new TextArea("",7,40,TextArea.SCROLLBARS_BOTH);

  30. bopen = new Button("open"); bsave = new Button("save"); badd = new Button("add"); bexit = new Button("exit"); bopen.addActionListener(this); bsave.addActionListener(this); badd.addActionListener(this); bexit.addActionListener(this); f.add(l1); f.add(addbook); f.add(l2); f.add(listbook);

  31. f.add(l1); f.add(addbook); f.add(l2); f.add(listbook); f.add(bopen); f.add(bsave); f.add(badd); f.add(bexit); badd.setEnabled(false); bsave.setEnabled(false); f.setSize(300,320); f.setVisible(true); }

  32. public void actionPerformed(ActionEvent e){ if (e.getSource() == bexit) System.exit(0); if (e.getSource() == bopen) { try {FileReader booklist = new FileReader("e:/temp/booklist.txt"); BufferedReader myin = new BufferedReader(booklist); for (int i=0; ; ) { String book = myin.readLine(); if (book == null) break; listbook.append(book+"\n"); savestring.addElement(book); }

  33. badd.setEnabled(true); bsave.setEnabled(true); myin.close(); booklist.close(); } catch (FileNotFoundException ee) { ee.printStackTrace(); } catch (IOException ee) { ee.printStackTrace(); } } // end of if (e.getSource() == bopen)

  34. if (e.getSource() == badd) { String txt=addbook.getText(); if (txt == null) return; else { listbook.append(txt+"\n"); savestring.addElement(txt); } } //end of if (e.getSource() == badd) if (e.getSource() == bsave) { try { FileWriter booklist = new FileWriter("e:/temp/booklist.txt"); PrintWriter myout = new PrintWriter(booklist);

  35. for (int i=0; i<savestring.size(); i++ ) { String book = savestring.elementAt(i).toString(); myout.print(book+"\n"); } myout.close(); booklist.close(); } catch (FileNotFoundException ee) { ee.printStackTrace(); }

  36. catch (IOException ee) { ee.printStackTrace(); } } //end of if (e.getSource() == bsave) } } 程序结果: 见演示.

  37. 10.6 随机访问文件 在任意位置读写文件. 1. 创建随机访问文件 打开随机访问文件有两种方法: l 用文件名 myRAFile=new RandomAccessFile(String name,String mode); 2 用文件对象 myRAFile=new RandomAccessFile(File file,String mode); mode参数决定了访问文件的权限,如只读'r'或读写'wr'等。 例如,我们打开一个数据库更新数据: RandomAccessFile myRAFile; myRAFile=new RandomAccessFile("/usr/db/stock.dbf","rw");

  38. 2. 访问信息 RandomAccessFile对象的读写操作和DataInput/DataOutput对象的操作方式一样。你可以使用在DataInputStream和DataOutputStream里出现的所有read()和write()函数。 还有几个函数帮助你在文件里移动指针: long getFilePointer();返回当前指针 void seek(long pos);将文件指针定位到一个绝对地址。地址是相对于文件头的偏移量。地址0表示文件的开头。 Long length();返回文件的长度。地址"length()"表示文件的结尾。 3. 增加信息 你可以使用随机访问文件来设置成增加信息模式: myRAFile=new RandomAccessFile("/tmp/java.log","rw"); myRAFile.seek(myRAFile.length());

  39. import java.io.IOException; import java.io.RandomAccessFile; class raTest{ public static void main(String args[]) throws IOException{ RandomAccessFile myRAFile; String s="Information to Append\n Hi mom!\n"; myRAFile=new RandomAccessFile("/tmp/java.log","rw"); //move to the end of the file myRAFile.seek(myRAFile.length()); //Start appending! myRAFile.writeBytes(s); myRAFile.close(); } }

More Related