Java编程语言中,想对文件进行操作,必须先对其封装的流操作类型有一定的了解。
对于计算机中的文件和目录,Java封装了一个File类。此类中定义了一些对文件及目录操作的常用方法
如果想不使用流方式操作文件,需要用到Java中定义的RandomAccessFile类。此类中定义了许多读写方法用于操作文件,如readInt, readLong, readShort, readDouble, readFloat, readBoolean, readChar, readLine;writeInt, writeLong, writeShort, writeDouble, writeFloat, writeBoolean writeChar, writeLine等。并可以使用seek方法移动指针,从文件任意位置进行读写操作。
对于文件的流操作,Java则提供了相对比较丰富的类。
InputStream,所有输入流类的祖先类,其子类有FileInputStream和FilterInputStream,而FilterInputStream下又有子类DataInputStream和BufferedInputStream.
OutStream,所有输出流类的祖先类,其子类有FileOutputStream和FilterOutputStream,而FilterOutputStream下又有子类DataOutputStream和BufferedOutputStream.
FileXXXXStream是以二进制方式对文件数据进行读写操作,使用read或write方法每次读取或写入一个或多个字节;
DataXXXXStream是对FileXXXXStream的一个装饰类,可以使用readInt(writeInt), readChar(writeChar), readBoolean(writeBoolean)等方法直接读取或写入数字、字符、布尔等类型数据;
BufferedXXXXStream亦是对FileXXXXStream的一个装饰类,其作用为可以使用缓冲区对流数据进行读取和写入操作。如果将FileXXXXStream类对数据的读取或写入比做是一瓢一瓢的将水接入大水桶,那么BufferedXXXXStream则是先将水接到一个小水桶中,然后再倒入存水的大水桶中。
下面举例说明这些类的使用方法。
public static void getFileInfo(String fileName) throws IOException { File f = new File(fileName); System.out.println("File Information [" + fileName + "]"); System.out.println("Executable: " + f.canExecute()); System.out.println("Writeable: " + f.canWrite()); System.out.println("Readable: " + f.canRead()); System.out.println("Path: " + f.getPath()); System.out.println("Absolute Paht: " + f.getAbsolutePath()); System.out.println("Canonical Path: " + f.getCanonicalPath()); System.out.println("Parten: " + f.getParent()); System.out.println("Last modified: " + f.lastModified()); System.out.println("Path: " + f.toPath()); System.out.println("URI: " + f.toURI()); System.out.println("======================================="); } //读取文本文件内容 public static void readFile(String fileName) throws IOException { //FileInputStream in = new FileInputStream(fileName); FileReader fr = new FileReader(fileName); int b; while ((b = fr.read()) != -1) { System.out.print((char)b); } fr.close(); }
public void copyFile(File srcFile, File destFile) { if (!srcFile.exists()) { //源文件不存在 throw new Exception("源文件" + srcFile + "不存在"); } if (!srcFile.isFile()) { //源文件不是文件,可是是目录或其他 throw new Exception("源文件" + srcFile + "不是文件"); } FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); InputStreamReader isr = new InputStreamReader(in); int b = 0; byte[] buf = new byte[8 * 1024]; while ((b = irs.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, b); } in.close(); out.close(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。