JAVA IO实例(经典)
java之IO技术

java之IO技术java的输出功能来自java.io包的InputStream类,OutputStream类,read 类和writer类,以及继承他们的各种子类,这些类以流的形式处理数据。
1.Inputstream类Inputstream类是字节输入流的抽象类,是所有字节输入的父类。
2.Outputstream类Outputstream类是字节输出流的抽象类,是所有字节输入的父类。
3.Reader类该类是字符输入流的抽象类,定义了操作字符输入流的各种方法4.Writer类用于解决字符输出流的类下面是使用上述类的例子代码public class ShuRuShuChu {public static void main(String [] args){ /*InputStream is=System.in;byte[] b=new byte[50];try {System.out.println("请输入内容 ");is.read(b);is.read(b,1,3);System.out.println(new String(b).trim());System.out.println(is.available());is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/ShuRuShuChu ac=new ShuRuShuChu();//ac.intPut();//ac.outPut();//ac.intPutread();ac.outPutwriter();}void outPut(){OutputStream out=System.out;try{String ass="456789";byte[] s=ass.getBytes();//byte[] s="ssyssyss".getBytes();out.write(s);out.close();}catch(IOException e){System.out.println("写入有误");}}void intPut(){InputStream is=System.in;byte[] b=new byte[50];try {System.out.println("请输入内容 ");is.read(b);//is.read(b,1,3);System.out.println(new String(b).trim());System.out.println(is.available());is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}void intPutread(){InputStreamReader ri=new InputStreamReader(System.in);char[] sd=new char[50];try{System.out.println("duru");ri.read(sd);ri.markSupported();System.out.println(ri.markSupported());String str=new String(sd);System.out.println(str);ri.close();}catch(IOException e){System.out.println("读入错误");}}void outPutwriter(){Writer writer=new PrintWriter(System.out);try{char ar[]="nisdshidfa".toCharArray();writer.write(ar);writer.flush();writer.close();}catch(IOException e){}}}5.文件字节输入/输出流文件字节输入流可以从指定路径的文件中读取字节数据。
iogame java 案例

iogame java 案例摘要:1.IO游戏简介2.Java编程语言简介3.IO游戏Java案例解析4.案例分析:游戏架构与核心玩法5.技术实现:网络通信与数据处理6.总结与拓展正文:IO游戏在近年来逐渐成为了一种热门的游戏类型,其特点是简单易懂、竞技性强,深受玩家喜爱。
而Java作为一种广泛应用于游戏开发的编程语言,更是开发者们的首选。
本文将为大家详细解析一个IO游戏的Java案例,分析其游戏架构、核心玩法,并探讨技术实现方面的问题。
1.IO游戏简介IO游戏,顾名思义,是指以互联网为基础,支持多人在线对战的游戏。
这类游戏通常具有快速响应、实时互动的特点,能够让玩家在短时间内体验到竞技的快感。
代表性的IO游戏有《Agario》、《Botzilla》等。
2.Java编程语言简介Java是一种面向对象的编程语言,具有跨平台、高效、安全等特点。
在游戏开发领域,Java有着广泛的应用。
许多知名的游戏引擎,如Unity3D,都支持使用Java进行编程。
此外,Java的生态系统丰富,有许多优秀的游戏开发库和框架,如Spike、LWJGL等。
3.IO游戏Java案例解析在这个案例中,我们以一款简单的多人在线贪吃蛇游戏为例,进行分析。
游戏的规则如下:玩家控制一个蛇形角色,通过吞食地图上的食物来增长身体,同时避免与其他玩家或自身碰撞。
游戏中,玩家需要争夺地图上的资源,竞争排名。
4.案例分析:游戏架构与核心玩法这款游戏的架构分为客户端和服务器端两部分。
客户端主要负责渲染画面、接收用户输入和发送游戏状态给服务器。
服务器端负责处理玩家间的互动、游戏状态同步和排行榜更新。
核心玩法包括:- 蛇形角色的移动和增长:玩家通过键盘或触摸屏控制蛇头方向,蛇头碰到食物后,尾部加入新食物,身体长度增加。
- 碰撞检测:蛇头碰到墙壁或自身、其他玩家时,游戏结束。
- 排行榜:根据玩家吞食食物的数量和游戏时长,实时更新排行榜。
5.技术实现:网络通信与数据处理游戏中,客户端与服务器之间的通信采用TCP/IP协议。
PPT26JavaIOJava程序设计实战案例教程

I/O流的分类
按照操作数据类型的不同,可以分为 字节流和字符流
按照数据传输方向的不同可分为输入 流和输出流,程序从输入流中读取数 据,向输出流中写入数据
public class BISDemo{ public static void main(String[]args)throws IOException{ // 创建一个缓冲输入流 BufferedInputStream bis=new BufferedInputStream(new FileInputStream("壁纸.jpg")); // 创建一个缓冲输出流 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("壁纸副本.jpg")); int len=0; long bt=System.currentTimeMillis();//获取文件复制前的系统时间 while((len=bis.read())!= -1){ bos.write(len); } long et=System.currentTimeMillis();//获取文件复制后的系统时间 System.out.println("文件复制用时:"+(et-bt)+"毫秒"); bis.close(); bos.close();
在代码实现前,准备好要复制的文件,如在当前项 目目录下存放一个“壁纸.jpg“文件。复制的代码如示 例8-6所示。
字节缓冲流
java io流的用法

Java I/O(Input/Output)流用于处理输入和输出数据。
在 Java 中,I/O 操作主要通过流(Stream)来完成。
流是一个有序的数据序列,它通过连接输入和输出设备来实现数据传输。
Java 中的 I/O 流可以分为两类:1. 字节流(Byte Streams):以字节为单位进行操作,适用于处理二进制数据,比如图像、音频、视频等。
- InputStream:用于从输入流读取字节数据。
- OutputStream:用于向输出流写入字节数据。
```java// 例子:使用 FileInputStream 读取文件import java.io.FileInputStream;import java.io.IOException;public class ReadFileExample {public static void main(String[] args) {try (FileInputStream fis = new FileInputStream("example.txt")) {int data;while ((data = fis.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();}}}```2. 字符流(Character Streams):以字符为单位进行操作,适用于处理文本数据。
- Reader:用于从输入流读取字符数据。
- Writer:用于向输出流写入字符数据。
```java// 例子:使用 FileReader 读取文件import java.io.FileReader;import java.io.IOException;public class ReadFileExample {public static void main(String[] args) {try (FileReader reader = new FileReader("example.txt")) {int data;while ((data = reader.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();}}}```注意:- 在 Java 7 及以上版本,可以使用 try-with-resources 语句自动关闭资源,无需显式调用 `close` 方法。
JAVA_20

第二十课Java流式I/O编程案例:2001 节点流应用举例案例文件:Test1.java目标:通过节点流实现文件复制功能,体会JavaI/O机制代码:/ * 范例名称:节点流应用举例* 源文件名称:Test1.java* 要点:* 1. Java I/O机制* 2. FileReader/FileWriter字节流类型的使用* 3. IOException的捕获和处理*/import java.io.*;public class Test1 {public static void main(String[] args) {try {FileReader input = new FileReader("Test1.java");FileWriter output = new FileWriter("temp.txt");int read = input.read();while ( read != -1 ) {output.write(read);read = input.read();}input.close();output.close();} catch (IOException e) {System.out.println(e);}}}Java辅助案例集案例:2002 缓冲功能处理流应用举例案例文件:Test2.java目标:通过处理流实现文件复制功能,体会JavaI/O流的封装/连接机制代码:/ * 范例名称:缓冲功能处理流应用举例* 源文件名称:Test2.java* 要点:* 1. Java I/O机制* 2. FileReader-BufferedReader/FileWriter-BufferedWriter的使用* 3. I/O流的封装和连接*/import java.io.*;public class Test2 {public static void main(String[] args) {try {FileReader input = new FileReader("Test2.java");BufferedReader br = new BufferedReader(input);FileWriter output = new FileWriter("temp.txt");BufferedWriter bw = new BufferedWriter(output);String s = br.readLine();while ( s!=null ) {bw.write(s);bw.newLine();s = br.readLine();}br.close();bw.close();} catch (IOException e) {e.printStackTrace();}}}案例:2003 ByteArrayInputStream应用举例案例文件:ByteArrayInputStreamTest.java目标:使用ByteArrayInputStream类型、掌握其用法代码:/ * 范例名称:ByteArrayInputStream应用举例* 源文件名称:ByteArrayInputStreamTest* 要点:* 1. ByteArrayInputStream类型功能及用法* 2. 字节流read()方法的返回值为int型*/import java.io.*;public class ByteArrayInputStreamTest{public static void main(String args[]){int ch;String str="Create a ByteArrayInputStream";byte buf[]=str.getBytes();ByteArrayInputStream bais=new ByteArrayInputStream(buf,7,7);System.out.println("可读取的字符数:"+bais.available());while((ch=bais.read())!=-1){System.out.print((char)ch);}System.out.println();}}案例:2004 临时文件的创建及使用案例文件:CreateTemp.java目标:掌握临时文件的创建及使用方法代码:/ * 范例名称:临时文件的创建及应用举例* 源文件名称:CreateTemp.java* 要点:* 1. File类对象既可对应文件,也可对应目录* 2. File类static方法createTempFile()用法* 3. 使用完毕后关闭输入/输出流对象与数据源间连接*/Java辅助案例集import java.io.*;public class CreateTemp{public static void main(String args[]){try{//创建File对象path,使之对应temp相对目录File path=new File("temp");//在path路径下创建临时文件"myfileXXXX.tmp"//XXXX 是系统自动产生的随机数, path对应的路径temp应事先存在File tempFile=File.createTempFile("myfile",".tmp",path);FileOutputStream fout=new FileOutputStream(tempFile);PrintStream out=new PrintStream(fout);out.println("安静劳动法立刻犯得上");out.close(); //注意:如无此关闭语句,文件将不能删除tempFile.delete();}catch(IOException e){System.out.println(e);}}}案例:2005 LineNumberReader类应用举例案例文件:PrintLines.java目标:掌握LineNumberXXX 类型使用方法代码:/* 范例名称:LineNumberReader类应用举例* 源文件名称:PrintLines.java* 要点:* 1. LineNumberReader类的使用* 2. 通过键盘输入终止程序运行*/import java.io.*;public class PrintLines {public static void main(String args[]) {InputStreamReader is = new InputStreamReader(System.in);LineNumberReader lineCounter=new LineNumberReader(is);String nextLine=null;System.out.println("输入任意字符串后回车,空回车或输入'exit'退出:");try {nextLine=lineCounter.readLine();while(!nextLine.equals("exit")){if(nextLine.length()==0) {//if(nextLine == null) {//if(nextLine == "") {break;}System.out.print(lineCounter.getLineNumber());System.out.print(":");System.out.println(nextLine);nextLine=lineCounter.readLine();}}catch(Exception e){e.printStackTrace();}}}。
Java IO编程

java i/o原理基本概念:∙I/O(Input/Output)∙数据源(Data Source)∙数据宿(Data Sink)Java中把不同的数据源与程序间的数据传输都抽象表述为"流"(Stream),java.io包中定义了多种I/O流类型实现数据I/O功能。
I/O流分类:∙输入流(Input Stream)和输出流(Output Stream)∙节点流(Node Stream)和处理流(Processing Stream)∙字符流(Character Stream)和字节流(Byte Stream)输入流和输出流按照数据流动的方向,java流可分为输入流(Input Stream)和输出流(Output Stream)∙输入流只能从中读取数据,而不能向其写出数据;∙输出流则只能向其写出数据,而不能从中读取数据∙特例:java.io.RandomAccessFile类节点流和处理流根据数据流所关联的是数据源还是其他数据流,可分为节点流(Node Stream)和处理流(Proce ssing Stream)∙节点流直接连接到数据源∙处理流是对一个已存在的流的连接和封装,通过封装的流的功能调用实现增强的数据读/写功能,处理流并不直接连接到数据源.字符流和字节流按传输数据的"颗粒大小"划分,可分为字符流(Character Stream)和字节流(Byte Stream)∙字节流以字节为单位进行数据传输,每次传送一个或多个字节;∙字符流以字符为单位进行数据传输,每次传送一个或多个字符.Java命名惯例:凡是以InputStream或OutputStream结尾的类型均为字节流,凡是以Reader或Writer结尾的均为字符流。
InputStream抽象类java.io.InputStream是所有字节输入流类型的父类,该类中定义了以字节为单位读取数据的基本方法,并在其子类中进行了分化和实现.三个基本的read方法:∙int read()∙int read(byte[] buffer)∙int read(byte[] buffer,int offset,int length)其他方法:∙void close()∙int available()∙skip(long n)∙boolean markSupported()InputStream类层次OutputStreamjava.io.OutputStream与java.io.InputStream对应,是所有字节输出流类型的抽象父类。
java io流的用法

java io流的用法Java IO流是Java编程中重要的一部分,它提供了丰富的功能,用于处理输入和输出。
本文将介绍Java IO流的基本用法和常见操作。
一、字节流和字符流的区别在Java IO流中,有字节流和字符流两种类型。
字节流用于处理字节数据,而字符流用于处理字符数据。
虽然字符数据可以通过字节流进行处理,但字符流更适合处理文本数据,因为它能够更好地处理字符编码和换行符等特殊字符。
二、字节流的用法字节流主要包括InputStream和OutputStream两个抽象类,分别用于从输入源读取数据和向输出目标写入数据。
常用的字节流有FileInputStream、FileOutputStream和ByteArrayInputStream、ByteArrayOutputStream等。
以文件操作为例,使用字节流读取文件的基本步骤如下:1. 创建一个File对象,指定要读取的文件路径。
2. 创建一个FileInputStream对象,将File对象作为参数传入构造方法。
3. 创建一个字节数组用于存储读取到的数据。
4. 使用read()方法读取字节数据,并将读取到的数据存入字节数组中。
使用字节流写入文件的基本步骤如下:1. 创建一个File对象,指定要写入的文件路径。
2. 创建一个FileOutputStream对象,将File对象作为参数传入构造方法。
3. 创建一个字节数组,将要写入的数据转换为字节数组。
4. 使用write()方法将字节数组写入输出流。
5. 写入结束后,关闭输出流。
三、字符流的用法字符流主要包括Reader和Writer两个抽象类,用于读取和写入字符数据。
常用的字符流有FileReader、FileWriter和BufferedReader、BufferedWriter等。
使用字符流读取文件的基本步骤如下:1. 创建一个File对象,指定要读取的文件路径。
2. 创建一个FileReader对象,将File对象作为参数传入构造方法。
java中的IO整理

【案例1】创建一个新文件 ?1 2 3 4 5 6 7 8 9 10 11 import java.io.*;class hello{public static void main(String[] args) {File f=new File("D:\\hello.txt");try{f.createNewFile();}catch (Exception e) {e.printStackTrace();}}}【运行结果】:程序运行之后,在d 盘下会有一个名字为hello.txt 的文件。
【案例2】File 类的两个常量 ?1 2 3 4 5 6 7 import java.io.*;class hello{public static void main(String[] args) {System.out.println(File.separator);System.out.println(File.pathSeparator);}}【运行结果】:\;此处多说几句:有些同学可能认为,我直接在windows 下使用\进行分割不行吗?当然是可以的。
但是在linux 下就不是\了。
所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。
呵呵、现在我们使用File 类中的常量改写上面的代码: ?1 2 3 4 5 6 7 8 9 10 11 12 import java.io.*;class hello{public static void main(String[] args) {String fileName="D:"+File.separator+"hello.txt";File f=new File(fileName);try{f.createNewFile();}catch (Exception e) {e.printStackTrace();}}}你看,没有多写多少吧,呵呵。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
建立文件路径(Constructing a Filename Path)String path = File.separator + "a" + File.separator + "b";在文件路径和Url之间进行转换(Converting Between a Filename Path and a URL)// Create a file objectFile file = new File("filename");// Convert the file object to a URLURL url = null;try {// The file need not exist. It is made into an absolute path// by prefixing the current working directoryurl = file.toURL(); // file:/d:/almanac1.4/java.io/filename} catch (MalformedURLException e) {}// Convert the URL to a file objectfile = new File(url.getFile()); // d:/almanac1.4/java.io/filename// Read the file contents using the URLtry {// Open an input streamInputStream is = url.openStream();// Read from isis.close();} catch (IOException e) {// Could not open the file}从相对文件路径取得绝对文件路径(Getting an Absolute Filename Path from a Relative Filename Path)File file = new File("filename.txt");file = file.getAbsoluteFile(); // c:\temp\filename.txtfile = new File("dir"+File.separatorChar+"filename.txt");file = file.getAbsoluteFile(); // c:\temp\dir\filename.txtfile = new File(".."+File.separatorChar+"filename.txt");file = file.getAbsoluteFile(); // c:\temp\..\filename.txt// Note that filename.txt does not need to exist判断是否两个文件路径是否指向同一个文件(Determining If Two Filename Paths Refer to the Same File)File file1 = new File("./filename");File file2 = new File("filename");// Filename paths are not equalboolean b = file1.equals(file2); // false// Normalize the pathstry {file1 = file1.getCanonicalFile(); // c:\almanac1.4\filenamefile2 = file2.getCanonicalFile(); // c:\almanac1.4\filename } catch (IOException e) {}// Filename paths are now equalb = file1.equals(file2); // true得到文件所在的文件夹名(Getting the Parents of a Filename Path)// Get the parent of a relative filename pathFile file = new File("Ex1.java");String parentPath = file.getParent(); // nullFile parentDir = file.getParentFile(); // null// Get the parents of an absolute filename pathfile = new File("D:\almanac\Ex1.java");parentPath = file.getParent(); // D:\almanacparentDir = file.getParentFile(); // D:\almanacparentPath = parentDir.getParent(); // D:\parentDir = parentDir.getParentFile(); // D:\parentPath = parentDir.getParent(); // nullparentDir = parentDir.getParentFile(); // null判断路径指向的是文件还是目录(Determining If a Filename Path Is a File or a Directory)File dir = new File("directoryName");boolean isDir = dir.isDirectory();if (isDir) {// dir is a directory} else {// dir is a file}判断文件或者路径是否存在(Determining If a File or Directory Exists)boolean exists = (new File("filename")).exists();if (exists) {// File or directory exists} else {// File or directory does not exist}创建文件(Creating a File)try {File file = new File("filename");// Create file if it does not existboolean success = file.createNewFile();if (success) {// File did not exist and was created} else {// File already exists}} catch (IOException e) {}得到文件的大小(Getting the Size of a File)File file = new File("infilename");// Get the number of bytes in the filelong length = file.length();删除文件(Deleting a File)boolean success = (new File("filename")).delete();if (!success) {// Deletion failed}创建临时文件(Creating a Temporary File)try {// Create temp file.File temp = File.createTempFile("pattern", ".suffix");// Delete temp file when program exits.temp.deleteOnExit();// Write to temp fileBufferedWriter out = new BufferedWriter(new FileWriter(temp));out.write("aString");out.close();} catch (IOException e) {}重命名一个文件或目录(Renaming a File or Directory)// File (or directory) with old nameFile file = new File("oldname");// File (or directory) with new nameFile file2 = new File("newname");// Rename file (or directory)boolean success = file.renameTo(file2);if (!success) {// File was not successfully renamed}移动文件或者目录(Moving a File or Directory to Another Directory)// File (or directory) to be movedFile file = new File("filename");// Destination directoryFile dir = new File("directoryname");// Move file to new directoryboolean success = file.renameTo(new File(dir, file.getName()));if (!success) {// File was not successfully moved}取得和修改文件或目录的修改时间(Getting and Setting the Modification Time of a File or Directory)This example gets the last modified time of a file or directory and then sets it to the current time.File file = new File("filename");// Get the last modified timelong modifiedTime = stModified();// 0L is returned if the file does not exist// Set the last modified timelong newModifiedTime = System.currentTimeMillis();boolean success = file.setLastModified(newModifiedTime);if (!success) {// operation failed.}强制更新硬盘上的文件(Forcing Updates to a File to the Disk)In some applications, such as transaction processing, it is necessary to ensure that an update has been made to the disk. FileDescriptor.sync() blocks until all changes to a file are written to disk.try {// Open or create the output fileFileOutputStream os = new FileOutputStream("outfilename");FileDescriptor fd = os.getFD();// Write some data to the streambyte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};os.write(data);// Flush the data from the streams and writers into system buffers.// The data may or may not be written to disk.os.flush();// Block until the system buffers have been written to disk.// After this method returns, the data is guaranteed to have// been written to disk.fd.sync();} catch (IOException e) {}得到当前的工作目录(Getting the Current Working Directory)The working directory is the location in the file system from where the java command was invoked.String curDir = System.getProperty("user.dir");创建目录(Creating a Directory)// Create a directory; all ancestor directories must existboolean success = (new File("directoryName")).mkdir();if (!success) {// Directory creation failed}// Create a directory; all non-existent ancestor directories are // automatically createdsuccess = (new File("directoryName")).mkdirs();if (!success) {// Directory creation failed}删除目录(Deleting a Directory)// Delete an empty directoryboolean success = (new File("directoryName")).delete();if (!success) {// Deletion failed}If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory. Here is a method that will delete a non-empty directory.// Deletes all files and subdirectories under dir.// Returns true if all deletions were successful.// If a deletion fails, the method stops attempting to delete and returns false.public static boolean deleteDir(File dir) {if (dir.isDirectory()) {String[] children = dir.list();for (int i=0; i<children.length; i++) {boolean success = deleteDir(new File(dir, children[i]));if (!success) {return false;}}}// The directory is now empty so delete itreturn dir.delete();}列举文件夹中的文件和子目录(Listing the Files or Subdirectories in a Directory)This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see e33 Traversing the Files and Directories Under a Directory.File dir = new File("directoryName");String[] children = dir.list();if (children == null) {// Either dir does not exist or is not a directory} else {for (int i=0; i<children.length; i++) {// Get filename of file or directoryString filename = children[i];}}// It is also possible to filter the list of returned files.// This example does not return any files that start with `.'.FilenameFilter filter = new FilenameFilter() {public boolean accept(File dir, String name) {return !name.startsWith(".");}};children = dir.list(filter);// The list of files can also be retrieved as File objectsFile[] files = dir.listFiles();// This filter only returns directoriesFileFilter fileFilter = new FileFilter() {public boolean accept(File file) {return file.isDirectory();}};files = dir.listFiles(fileFilter);列举系统根目录下的文件(Listing the File System Roots)UNIX file systems have a single root, `/'. On Windows, each drive is a root. For example the C drive is represented by the root C:\.File[] roots = File.listRoots();for (int i=0; i<roots.length; i++) {process(roots[i]);}遍历目录(Traversing the Files and Directories Under a Directory)This example implements methods that recursively visits all files and directories under a directory.// Process all files and directories under dirpublic static void visitAllDirsAndFiles(File dir) {process(dir);if (dir.isDirectory()) {String[] children = dir.list();for (int i=0; i<children.length; i++) {visitAllDirsAndFiles(new File(dir, children[i]));}}}// Process only directories under dirpublic static void visitAllDirs(File dir) {if (dir.isDirectory()) {process(dir);String[] children = dir.list();for (int i=0; i<children.length; i++) {visitAllDirs(new File(dir, children[i]));}}}// Process only files under dirpublic static void visitAllFiles(File dir) {if (dir.isDirectory()) {String[] children = dir.list();for (int i=0; i<children.length; i++) {visitAllFiles(new File(dir, children[i]));}} else {process(dir);}}从控制台读入文本(Reading Text from Standard Input)try {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String str = "";while (str != null) {System.out.print("> prompt ");str = in.readLine();process(str);}} catch (IOException e) {}从文件中读入文本(Reading Text from a File)try {BufferedReader in = new BufferedReader(new FileReader("infilename"));String str;while ((str = in.readLine()) != null) {process(str);}in.close();} catch (IOException e) {}将文件内容读入一个Byte型数组(Reading a File into a Byte Array)This example implements a method that reads the entire contents of a file into a byte array.See also e35 Reading Text from a File.// Returns the contents of the file in a byte array.public static byte[] getBytesFromFile(File file) throws IOException {InputStream is = new FileInputStream(file);// Get the size of the filelong length = file.length();// You cannot create an array using a long type.// It needs to be an int type.// Before converting to an int type, check// to ensure that file is not larger than Integer.MAX_V ALUE.if (length > Integer.MAX_V ALUE) {// File is too large}// Create the byte array to hold the databyte[] bytes = new byte[(int)length];// Read in the bytesint offset = 0;int numRead = 0;while (offset < bytes.length&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {offset += numRead;}// Ensure all the bytes have been read inif (offset < bytes.length) {throw new IOException("Could not completely read file "+file.getName());}// Close the input stream and return bytesis.close();return bytes;}写文件(Writing to a File)If the file does not already exist, it is automatically created.try {BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));out.write("aString");out.close();} catch (IOException e) {}向文件中添加内容(Appending to a File)try {BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));out.write("aString");out.close();} catch (IOException e) {}使用随即存取文件(Using a Random Access File)try {File f = new File("filename");RandomAccessFile raf = new RandomAccessFile(f, "rw");// Read a characterchar ch = raf.readChar();// Seek to end of fileraf.seek(f.length());// Append to the endraf.writeChars("aString");raf.close();} catch (IOException e) {}从文件中阅读UTF-8格式的数据(Reading UTF-8 Encoded Data)try {BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("infilename"), "UTF8"));String str = in.readLine();} catch (UnsupportedEncodingException e) {} catch (IOException e) {}向文件中写入UTF-8格式的数据(Writing UTF-8 Encoded Data)try {Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename"), "UTF8"));out.write(aString);out.close();} catch (UnsupportedEncodingException e) {} catch (IOException e) {}从文件中阅读ISO Latin-1格式的数据(Reading ISO Latin-1 Encoded Data)try {BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("infilename"), "8859_1"));String str = in.readLine();} catch (UnsupportedEncodingException e) {} catch (IOException e) {}向文件中写入ISO Latin-1 格式的数据(Writing ISO Latin-1 Encoded Data)try {Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename"), "8859_1"));out.write(aString);out.close();} catch (UnsupportedEncodingException e) {} catch (IOException e) {}序列化实体(Serializing an Object)The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.See also e45 Deserializing an Object.Object object = new javax.swing.JButton("push me");try {// Serialize to a fileObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));out.writeObject(object);out.close();// Serialize to a byte arrayByteArrayOutputStream bos = new ByteArrayOutputStream() ;out = new ObjectOutputStream(bos) ;out.writeObject(object);out.close();// Get the bytes of the serialized objectbyte[] buf = bos.toByteArray();} catch (IOException e) {}反序列化实体(Deserializing an Object)This example deserializes a javax.swing.JButton object.See also e44 Serializing an Object.try {// Deserialize from a fileFile file = new File("filename.ser");ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));// Deserialize the objectjavax.swing.JButton button = (javax.swing.JButton) in.readObject();in.close();// Get some byte array databyte[] bytes = getBytesFromFile(file);// see e36 Reading a File into a Byte Array for the implementation of this method// Deserialize from a byte arrayin = new ObjectInputStream(newByteArrayInputStream(bytes));button = (javax.swing.JButton) in.readObject();in.close();} catch (ClassNotFoundException e) {} catch (IOException e) {}Implementing a Serializable SingletonBy default, the deserialization process creates new instances of classes. This example demonstrates how to customize the deserialization process of a singleton to avoid creating new instances of the singleton.public class MySingleton implements Serializable {static MySingleton singleton = new MySingleton();private MySingleton() {}// This method is called immediately after an object of this class is deserialized.// This method returns the singleton instance.protected Object readResolve() {return singleton;}}Tokenizing Java Source CodeThe StreamTokenizer can be used for simple parsing of a Java source file into tokens. The tokenizer can be aware of Java-style comments and ignore them. It is also aware of Java quoting and escaping rules.try {// Create the tokenizer to read from a fileFileReader rd = new FileReader("filename.java");StreamTokenizer st = new StreamTokenizer(rd);// Prepare the tokenizer for Java-style tokenizing rulesst.parseNumbers();st.wordChars('_', '_');st.eolIsSignificant(true);// If whitespace is not to be discarded, make this callst.ordinaryChars(0, ' ');// These calls caused comments to be discardedst.slashSlashComments(true);st.slashStarComments(true);// Parse the fileint token = st.nextToken();while (token != StreamTokenizer.TT_EOF) {token = st.nextToken();switch (token) {case StreamTokenizer.TT_NUMBER:// A number was found; the value is in nvaldouble num = st.nval;break;case StreamTokenizer.TT_WORD:// A word was found; the value is in svalString word = st.sval;break;case '"':// A double-quoted string was found; sval contains the contentsString dquoteVal = st.sval;break;case '\'':// A single-quoted string was found; sval contains thecontentsString squoteVal = st.sval;break;case StreamTokenizer.TT_EOL:// End of line character foundbreak;case StreamTokenizer.TT_EOF:// End of file has been reachedbreak;default:// A regular character was found; the value is the token itselfchar ch = (char)st.ttype;break;}}rd.close();} catch (IOException e) {}。