Java语言程序设计(文件输入输出、Java网络编程)ppt.ppt_第1页
Java语言程序设计(文件输入输出、Java网络编程)ppt.ppt_第2页
Java语言程序设计(文件输入输出、Java网络编程)ppt.ppt_第3页
Java语言程序设计(文件输入输出、Java网络编程)ppt.ppt_第4页
Java语言程序设计(文件输入输出、Java网络编程)ppt.ppt_第5页
已阅读5页,还剩78页未读 继续免费阅读

下载本文档

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

文档简介

1,Java语言程序设计,马 皓,2,第九章 文件输入输出,概念 Java I/O类 Java I/O操作 标准输入/输出 文件读写操作 目录管理 随机访问文件 文件属性,3,概念,I/O来源 控制台(console, 如DOS窗口)打印/读入 文件(file)读/写 网络接口(TCP/UDP端口)读/写 针对数据的读写 以流(stream)的方式对数据进行操作,流的重要特性 顺序读/写 sequentially,4,概念,读/写流的一般流程 读(Reading) open a stream /打开读出流 while more information /判断 read information /读 close the stream /关闭流 写(Writing) open a stream /打开写入流 while more information /判断 write information /写 close the stream /关闭流,5,概念,两种流的定义(读取信息的基本数据单位) 字节流(byte stream): 一个字节(8-bit)一个字节读/写 字符流(character stream):一个字符一个字符读/写(具有特定字符编码的数据),j a v a 语 言 6A 61 76 61 D3 EF D1 D4 以字节流的方式读: 读8次,8个字节 以字符流的方式读: 读6次,6个字符,6,第九章 文件输入输出,概念 Java I/O类 Java I/O操作 标准输入/输出 文件读写操作 目录管理 随机访问文件 文件属性,7,Java I/O类,字节流的读/写操作(来自JDK1.0) java.io.InputStream (抽象类) public abstract int read() public int read(byte b) public int read(byte b, int offset, int length) 到达流的终点,无数据读出则返回-1 java.io.OutputStream (抽象类) public abstract void write(int b) public void write(byte b) public void write(byte b, int offset, int length) 所有的读/写函数都抛出java.io.IOException,8,Java I/O类,字符流的读/写操作(来自JDK1.1) java.io.Reader (抽象类) public int read() public int read(char cbuf) publc abstract int read(char cbuf, int offset, int length) 到达流的终点,无数据读出则返回-1 java.io.Writer (抽象类) public void write(int c) public void write(char cbuf) public void write(char cbuf, int offset, int length) 所有的读/写函数都抛出java.io.IOException,9,Java I/O类,I/O流的层次关系 class java.io.InputStream的子类 class java.io.ByteArrayInputStream class java.io.FileInputStream class java.io.FilterInputStream class java.io.BufferedInputStream class java.io.DataInputStream class java.io.LineNumberInputStream class java.io.PushbackInputStream class java.io.ObjectInputStream class java.io.PipedInputStream class java.io.SequenceInputStream class java.io.StringBufferInputStream ,10,Java I/O类,I/O流的层次关系 class java.io.OutputStream的子类 class java.io.ByteArrayOutputStream class java.io.FileOutputStream class java.io.FilterOutputStream class java.io.BufferedOutputStream class java.io.DataOutputStream class java.io.PrintStream class java.io.ObjectOutputStream class java.io.PipedOutputStream ,11,Java I/O类,I/O流的层次关系 class java.io.Reader的子类 class java.io.BufferedReader class java.io.LineNumberReader class java.io.CharArrayReader class java.io.FilterReader class java.io.PushbackReader class java.io.InputStreamReader class java.io.FileReader class java.io.PipedReader class java.io.StringReader ,12,Java I/O类,I/O流的层次关系 class java.io.Writer的子类 class java.io.BufferedWriter class java.io.CharArrayWriter class java.io.FilterWriter class java.io.OutputStreamWriter class java.io.FileWriter class java.io.PipedWriter class java.io.PrintWriter class java.io.StringWriter ,13,Java I/O类,I/O流的分类 (12个功能类),14,Java I/O类,I/O流的分类 (12个功能类),15,Java I/O类,I/O流的分类 (12个功能类),16,第九章 文件输入输出,概念 Java I/O类 Java I/O操作 标准输入/输出 文件读写操作 目录管理 随机访问文件 文件属性,17,Java I/O操作,主要内容 标准输入/输出 控制台屏幕打印和键盘读入 文件I/O操作 文件读写 如何提高文件读写效率 流的包装(Wrap) 基本数据转换流 目录管理 随机访问文件(Random Access File) 文件属性 网络流操作(见第十三讲),18,输出: 控制台屏幕打印 class Test public static void main(String args) System.out.println(“Hello World!”); ,标准输入/输出,19,输入: 键盘读入 import java.io.IOException; class Test public static void main(String args) throws IOException byte b = new byte10; System.out.println(“Received number=“ + System.in.read(b); ,标准输入/输出,C:java Test A Received number=3 C:,20,文件读/写流程 打开文件流 条件判断 读出/写入 关闭文件流 两种类型文件 FileInputStream/FileOutputStream (字节流) FileReader/FileWriter (字符流),文件读写操作,21,字节流构造方法 public FileInputStream(File file) throws FileNotFoundException public FileInputStream(String name) throws FileNotFoundException public File(String pathname) public FileOutputStream(File file) throws FileNotFoundException public FileOutputStream(File file, boolean append) throws FileNotFoundException /是否向已存在的文件后添加 public FileOutputStream(String name) throws FileNotFoundException public FileOutputStream(String name, boolean append) throws FileNotFoundException,文件读写操作,22,文件读写-实例1,文件读写操作,import java.io.*; public class CopyBytes public static void main(String args) throws IOException File inputFile = new File(“original.txt“); File outputFile = new File(“result.txt“); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while (c = in.read() != -1) out.write(c); in.close(); out.close(); ,public int read ()throws IOException public int read (byte b) throws IOException public int read (byte b, int off, int len) throws IOException,FileInputStream in = new FileInputStream(“original.txt“); FileOutputStream out = new FileOutputStream(“result.txt“);,public void write (int b) throws IOException public void write (byte b) throws IOException public void write (byte b, int off, int len) throws IOException,23,字符流构造方法 public FileReader(File file) throws FileNotFoundException public FileReader(String fileName) throws FileNotFoundException public File(String pathname) public FileWriter(File file) throws IOException public FileWriter(File file, boolean append) throws IOException public FileWriter(String fileName) throws IOException public FileWriter(String fileName, boolean append) throws IOException,文件读写操作,24,文件读写-实例2,文件读写操作,import java.io.*; public class Copy public static void main(String args) throws IOException File inputFile = new File(“original.txt“); File outputFile = new File(“result.txt“); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while (c = in.read() != -1) out.write(c); in.close(); out.close(); ,FileReader in = new FileReader(“original.txt“); FileWriter out = new FileWriter(“result.txt“);,public int read () throws IOException public int read (char cbuf) throws IOException public int read (char cbuf, int off, int len) throws IOException,public void write (int b) throws IOException public void write (char cbuf) throws IOException public void write (char cbuf, int off, int len) throws IOException,25,两类缓冲流 针对字节流 java.io.BufferedInputStream类 java.io.BufferedOutputStream类 针对字符流 java.io.BufferedReader类 java.io.BufferedWriter类,如何提高文件读写效率,26,构造方法 public BufferedInputStream(InputStream in) 2048 bytes public BufferedInputStream(InputStream in, int size) public BufferedOutputStream(OutputStream out) 512 bytes public BufferedOutputStream(OutputStream out, int size) public BufferedReader(Reader in) 8192 bytes public BufferedReader(Reader in, int sz) public BufferedWriter(Writer out) 8192 byte public BufferedWriter(Writer out, int sz),如何提高文件读写效率,27,String filename = “test.txt”; FileInputStream fis = new FileInputStream(filename); int count = 0; int c; while (c = fis.read() != -1) if (c = A) count+; fis.close(); System.out.println(count);,如何提高文件读写效率-实例1,如何提高文件读写效率,String filename = “test.txt”; FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); int count = 0; int c; while (c = bis.read() != -1) if (c = A) count+; fis.close(); System.out.println(count);,FileInputStream fis = new FileInputStream(“test.txt”); int count = 0; final int BUFSIZE = 1024; byte buf = new byteBUFSIZE; int len; while (len = fis.read(buf) != -1) for (int i = 0; i len; i+) if (bufi = A) count+; fis.close();,28,String filename = “test.txt”; FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); int count = 0; while (br.readLine() != null) count+; br.close(); System.out.println(count);,如何提高文件读写效率-实例2,如何提高文件读写效率,29,概述,流的包装(wrap),FileReader fr = new FileReader (filename); BufferedReader br = new BufferedReader (fr);,BufferedReader br = new BufferedReader ( new FileReader(filename);,PrintWriter out = new PrintWriter ( new BufferedWriter(new FileWriter(filename);,public String readLine() in java.io.BufferedReader public void println(String x) in java.io.PrintWriter,利用不同流的特点(方法) 寻找合适的方法完成特定的需求 对已有的流进行再处理,30,流的种类 节点流 直接对数据源进行读/写操作的流 处理流 对一个已有的流进行某种操作的流,流的包装(wrap),31,节点流 FileInputStream, PipedInputStream, ByteArrayInputStream, StringBufferInputStream FileOutputStream, PipedOutputStream, ByteArrayOutputStream CharArrayReader, FileReader, PipedReader, StringReader CharArrayWriter, FileWriter, PipedWriter, StringWriter,流的包装(wrap),32,处理流 FilterOutputStream, DataOutputStream, BufferedOutputStream, PrintStream FilterInputStream, LineNumberInputStream, DataInputStream, BufferedInputStream, PushbackInputStream BufferedReader, LineNumberReader, InputStreamReader, FilterReader, PushBackReader BufferedWriter, OutputStreamReader, FilterWriter, PrintWriter,流的包装(wrap),33,一个实例 java.io.FileReader public FileReader(File file) throws FileNotFoundException public FileReader(String fileName) throws FileNotFoundException java.io.BufferedReader public BufferedReader(Reader in) 8192 bytes public BufferedReader(Reader in, int sz) 流的包装改变了流的行为,流的包装(wrap),34,流的包装(wrap)-实例1,流的包装(wrap),import java.io.*; public class Echo public static void main(String args) throws IOException BufferedReader in = new BufferedReader( new InputStreamReader(System.in); String s; while(s = in.readLine().length() != 0) System.out.println(s); ,public static final InputStream in (java.lang.System) public InputStreamReader(InputStream in) public BufferedReader(Reader in),程序如何结束(跳出while循环)?,35,概述 java.io.DataInputStream类 public DataInputStream(InputStream in) public final boolean readBoolean() public final byte readByte() public final char readChar() public final int readInt() java.io.DataOutputStream类 public DataOutputStream(OutputStream out) public final void writeBoolean(boolean v) public final void writeByte(int v) public final void writeChar(int v) public final void writeInt(int v),基本数据转换流,36,DataOutputStream out = new DataOutputStream(new FileOutputStream(“invoice1.txt“); double prices = 19.99, 9.99; int units= 12, 8; String descs = “Java T-shirt“, “Java Mug“; for (int i = 0; i prices.length; i +) out.writeDouble(pricesi); out.writeChar(t); out.writeInt(unitsi); out.writeChar(t); out.writeChars(descsi); out.writeChar(n); out.close();,基本数据转换流-实例,基本数据转换流,DataInputStream in = new DataInputStream( new FileInputStream(“invoice1.txt“); double total; try while (true) double price = in.readDouble(); in.readChar(); int unit = in.readInt(); in.readChar(); char chr; StringBuffer desc = new StringBuffer(20); while (chr = in.readChar()!= n) desc.append(chr); System.out.println(“Youve ordered “ + unit + “ units of “ + desc + “ at $“ + price); total = total + unit * price; catch (EOFException e) System.out.println(“For a TOTAL of: $“ + total); in.close();,19.99 12 Java T-shirt 9.99 8 Java Mug,37,概述 java.io.File类: 文件和目录的路径名 构造方法 public File(String pathname) public File(String parent, String child) public File(File parent, String child) parent通常表示一个目录, child则表示一个目录或文件 路径名(pathname) UNIX平台上绝对路径的前缀“/”,相对路径无前缀,例“/etc/inetd.conf”、“inetd.conf” Windows平台,绝对路径名的前缀由“盘符:”组成;UNC 路径名前缀为“”,然后是主机名和共享名,相对路径名无盘符,例“c:windowsnotepad.exe”、“notepad.exe”,目录管理,38,方法 public boolean canWrite()/canRead() public boolean exists() public boolean delete() 删除文件或目录,若删除目录,要求该目录必须为空 public boolean createNewFile() 创建一个空文件,当且仅当该文件不存在 public boolean isDirectory()/isFile()/isHidden() public long lastModified()/public boolean setLastModified(long time) public String list() 得到当前目录下的所有文件名和目录名,若该File对象不是表示目录,则返回null public boolean mkdir()/mkdirs() 创建一个目录 public boolean renameTo(File dest) public boolean setReadOnly(),目录管理,39,目录管理方法举例,目录管理,import java.io.File; public class DirList public static void main(String args) File path = new File(“.“); String list = path.list(); for(int i = 0; i list.length; i+) System.out.println(listi); ,40,目录管理方法举例,目录管理,import java.io.File; import java.io.FilenameFilter; public class DirList public static void main(String args) File path = new File(“.“); String list = path.list(new DirFilter(args0); for (int i = 0; i list.length; i+) System.out.println(listi); ,class DirFilter implements FilenameFilter String key; DirFilter(String key) this.key = key; public boolean accept(File dir, String name) String f = new File(name).getName(); return f.indexOf(key) != -1; ,java.util.FilenameFilter 接口 public boolean accept(File dir, String name); /是否指定的文件应包含在文件列表中,public String getName() in java.io.File /获得文件或目录名,仅仅是最后的部分,41,随机访问文件(Random Access File) java.io.RandomAccessFile类 读写操作在同一个类中完成,须在构造对象时指定参数 通过移动文件指针(file pointer)在文件的指定位置进行读写操作 构造方法 public RandomAccessFile(String name, String mode) throws FileNotFoundException public RandomAccessFile(File file, String mode) throws FileNotFoundException mode: “r”, “rw”,随机访问文件,42,方法 public void seek(long pos) public int read() public int read(byte b) public int read(byte b, int off, int len) public final boolean readBoolean()/readByte()/readChar()/readShort()/readInt()/readDouble()/readFloat() public final String readLine() public void write(int b) public void write(byte b) public void write(byte b, int off, int len) public final void writeBoolean()/writeByte()/writeChar()/writeShort()/writeInt()/writeDouble()/writeFloat(),随机访问文件,43,随机访问文件(Random Access File)-实例,随机访问文件,RandomAccessFile rf = new RandomAccessFile(“rtest.dat“, “rw“); for(int i = 0; i 10; i+) rf.writeDouble(i*1.414); rf.close(); rf = new RandomAccessFile(“rtest.dat“, “rw“); rf.seek(5*8); rf.writeDouble(47.0001); rf.close(); rf = new RandomAccessFile(“rtest.dat“, “r“); for(int i = 0; i 10; i+) System.out.println(“Value “ + i + “: “ + rf.readDouble(); rf.close();,运行结果: Value 0: 0.0 Value 1: 1.414 Value 2: 2.828 Value 3: 4.242 Value 4: 5.656 Value 5: 47.0001 Value 6: 8.484 Value 7: 9.898 Value 8: 11.312 Value 9: 12.725999999999999,44,文件的特性 读和写的权限 文件长度 修改时间 是否是目录 java.io.File类 设定文件属性 查询文件属性,文件属性,45,文件属性,获取文件路径,import java.io.*; class AttrDemo1 public static void main(String args) throws IOException File testfile = new File(“.“ + File.separatorChar + “testfile1“); testfile.createNewFile(); System.out.println(“name = “ + testfile.getName(); System.out.println(“path = “ + testfile.getPath(); System.out.println(“absolute path = “ + testfile.getAbsolutePath(); System.out.println(“canonical path = “ + testfile.getCanonicalPath(); ,46,文件属性,获取文件修改时间,import java.io.*; import java.util.*; public class AttrDemo2 public static void main(String args) throws IOException File testfile = new File(“testfile2“); testfile.delete(); testfile.createNewFile(); long modtime = testfile.lastModified(); System.out.println(“last modification time #1 = “ + new Date(modtime); testfile.setLastModified(0); modtime = testfile.lastModified(); System.out.println(“last modification time #2 = “ + new Date(modtime); ,47,文件属性,获取和设定文件长度,import java.io.*; public class AttrDemo3 public static void main(String args) throws IOException File testfile = new File(“testfile3“); testfile.delete(); testfile.createNewFile(); System.out.println(“length #1 = “ +testfile.length(); RandomAccessFile raf = new RandomAccessFile(“testfile3“, “rw“); raf.setLength(100); raf.close(); System.out.println(“length #2 = “ + testfile.length(); ,48,文件属性,设置读写权限,import java.io.*; public class AttrDemo4 public static void main(String args) throws IOException File testfile = new File(“testfile4“); testfile.delete(); testfile.createNewFile(); if (testfile.canRead() System.out.println(“file can be read #1“); if (testfile.canWrite() System.out.println(“file can be written #1“); testfile.setReadOnly(); if (testfile.canRead() System.out.println(“file can be read #2“); if (testfile.canWrite() System.out.println( “file can be written #2“); ,49,第九章 结束 !,50,概述 URL应用 Socket应用 UDP数据报,第十章 Java网络编程,51,概述,The Java platform is highly regarded in part because of its suitability for writing programs that use and interact with the resources on the Internet and the World Wide Web.,52,概述,Applet Applet程序嵌在HTML文件中,通过网络下载Applet程序代码,在本地Java-enabled browser 中执行 HTTP 通过URL类获取服务器端的HTML文件 Socket(套接字) 实现Client/Server结构的应用 JDBC (Java Database Connectivity) 通过网络访问关系型数据库 Oracle, MS SQL, Sybase Servlet/JSP (Java Server Page) WEB服务器端的动态编程,53,概述,网络基础-TCP/IP协议簇 网络层(Network Layer) Internet Protocol (IP), IP地址, 32比特 传输层(Transport Layer) 传输控制协议(TCP: Transport Control Protocol) 用户数据报协议(UDP: User Datagram Protocol) 端口(Port, 16比特, 065535) 应用层(Application Layer) HTTP, FTP, SMTP, POP3, Telnet, DNS,TCP or UDP,Port,应用,Port,Port,Port,Port,数据1,应用,应用,应用,Port,数据2,主机,54,概述,Java语言中基本网络类 Package .URL .URLConnection .Socket .ServerSocket .DatagramPacket .DatagramSocket .MulticastSocket,55,概述 URL应用 Socket应用 UDP数据报,第十章 Java网络编程,56,URL应用,什么是URL? 统一资源定位符(Uniform Resource Locator) a reference (an address, a pointer) to a resource on the Internet.,http,,:/,协议标识符,资源名 (主机名, 端口号, 文件名),http,/index.html,:/,ftp,/pub/,:/,57,URL应用,.URL类 构造方法 public URL(String spec) throws MalformedURLException public URL(String protocol, String host, String file) throws MalformedURLException public URL(String protocol, String host, int port, String file) throws MalformedURLException 实例方法 public final InputStream openStream() throws IOException Opens a connection to this URL and returns an InputStream for reading from that connection public URLConnection openConnection() throws IOException Returns a URLConnection object that represents a connection to the remote object referred to by the URL,58,URL应用,.URL类-示例 “/” new URL(““); /academic/index.html new URL(“/academic/index.html“); new URL(“http“, ““, “/academic/index.html“); new URL(“http“, ““, 80, “/academic/index.html“);,59,URL应用,实例,import .*; import java.io.*; public class URLReader public static void main(String args) throws Exception URL pku = new URL(““); BufferedReader in =

温馨提示

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

评论

0/150

提交评论