操作文件的类–File
在整个IO包中,唯一与文件本身有关的就是File类,使用File类可以进行创建或删除文件等操作。 File类常用构造方法:
public File ( String pathName) ;
方法或常量 描述 public static final String pathSeparator 常量:表示路径的分隔符(windows是:“;”) public static final String separator 常量:表示路径的分隔符(windows是:“\”) public File(String pathName) 创建File类的对象,传入完整路径 public boolean creatNewFile() throws IOException 创建新文件 public boolean delete() 删除文件 public boolean exists() 判断文件是否存在 public boolean isDirectory() 判断给定的路径是否是一个目录 public long length() 返回文件的大小 public String[] list() 列出指定文件目录的全部内容,只是列出了名称 public File[] listFiles() 列出指定目录的全部内容,会列出路径 public boolean mkdir() 创建一个目录 public boolean renameTo() 将已有的文件重新命名
使用File类操作文件
File类的对象实例化完成后,就可以使用creatNewFile()创建一个新文件,但此方法使用了throws关键字声明,因此必须使用try…catch进行异常处理。 创建新的文件:
import java. io. File ;
import java. io. IOException ;
public class FileTest {
public static void main ( String [ ] args) {
File file = new File ( "E:\\daima\\java\\IO\\src\\File\\test\\test1.txt" ) ;
try {
file. createNewFile ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "pathSeparator: " + File . pathSeparator) ;
System . out. println ( "separator:" + File . separator) ;
}
}
file. delete ( ) ;
if ( file. exists ( ) ) {
file. delete ( ) ;
}
在每次执行完毕后,文件并不会立刻创建或删除,会有一些延迟,这是因为所有的
操作都要通过JVM完成所造成的。
File file1 = new File ( "E:\\daima\\java\\IO\\src\\File\\test\\books" ) ;
file1. mkdir ( ) ;
File file2 = new File ( "E:\\daima\\java\\IO" ) ;
String str[ ] = file2. list ( ) ;
for ( int i = 0 ; i < str. length; i++ ) {
System . out. println ( str[ i] ) ;
}
File files[ ] = file2. listFiles ( ) ;
for ( int i = 0 ; i < str. length; i++ ) {
System . out. println ( files[ i] ) ;
}
if ( file2. isDirectory ( ) ) {
System . out. println ( file2. getPath ( ) + "路径是目录。" ) ;
} else {
System . out. println ( file2. getPath ( ) + "不是目录。" ) ;
}
RandomAccessFile类
此类为随机读取类,可以随机读取一个文件中指定位置的数据。 RandomAccessFile类的常用操作方法:
方法 描述 public RandomAccessFile(File file,String mode)throws FileNotFoundException 接受File类的对象,指定操作路径,但是在设置时需要设置模式,r为只读;w为只写,rw为读写。 public RandomFileAccessFile(String name,String mode)throws FileNotFoundException 不再使用File类对象表示文件,而是直接输入了固定的文件路径。 public void close()throws IOException 关闭操作。 public int read(byte[] b)throws IOException 将内容读取到一个byte数组中。 public final byte readByte()throws IOException 读取一个字节。 public final int readInt()throws IOException 从文件中读取整型数据。 public void seek(long pos)throws IOException 设置读指针的位置。 public final void writeBytes(String s)throws IOException 将一个字符串写入到文件中,按字节的方式处理。 public final void writeInt(int v)throws IOException 将一个int型数据写入文件,长度为4位。 public int skipBytes(int n)throws IOException 将指针跳过指定的字节。
import java. io. File ;
import java. io. RandomAccessFile ;
public class RandomAccessFileTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\randaccf\\test.txt" ) ;
RandomAccessFile rdf = new RandomAccessFile ( file, "rw" ) ;
String name = null ;
int age = 0 ;
name = "zhangsan" ;
age = 25 ;
rdf. writeBytes ( name) ;
rdf. writeInt ( age) ;
name = "lisi" ;
age = 23 ;
rdf. writeBytes ( name) ;
rdf. writeInt ( age) ;
name = "wangwu" ;
age = 30 ;
rdf. writeBytes ( name) ;
rdf. writeInt ( age) ;
rdf. close ( ) ;
}
}
写完后可以通过Random Access的方式进行读取。
RandomAccessFile raf = new RandomAccessFile ( file, "r" ) ;
byte b[ ] = new byte [ 8 ] ;
raf. skipBytes ( 12 ) ;
for ( int i = 0 ; i < b. length; i++ ) {
b[ i] = raf. readByte ( ) ;
}
name = new String ( b) ;
age = raf. readInt ( ) ;
System . out. println ( "第二个人的信息-->姓名:" + name + "年龄:" + age) ;
raf. seek ( 0 ) ;
b = new byte [ 8 ] ;
for ( int i = 0 ; i < b. length; i++ ) {
b[ i] = raf. readByte ( ) ;
}
name = new String ( b) ;
age = raf. readInt ( ) ;
System . out. println ( "第一个人的信息-->姓名:" + name + "年龄:" + age) ;
raf. skipBytes ( 12 ) ;
b = new byte [ 8 ] ;
for ( int i = 0 ; i < b. length; i++ ) {
b[ i] = raf. readByte ( ) ;
}
name = new String ( b) ;
age = raf. readInt ( ) ;
System . out. println ( "第三个人的信息-->姓名:" + name + "年龄:" + age) ;
字节流与字符流基本操作
程序中所有的数据都是以流的方式进行传输或者保存的,程序需要时要使用输入流数据读取存入数据,而当程序需要将一些数据保存起来时,就要使用输出流。 java.io中的操作主要包括字节流、字符流两大类,两类都有输入和输出的操作。在字节流中输出要用OutputStream类完成,输入则用InputStream类。在字符流中输出主要是用Writer完成,输入主要是用Reader完成。 IO操作步骤:
使用File类打开一个文件。 通过字节流或字符流的子类指定输出的位置。 进行读/写操作。 关闭输入/输出。
字节流
字节输出流:OutputStream
OutputStream是整个IO包中字节输出流最大父类,定义:
public abstract class OutputStream extends Object implements Closeable ,Flushable
方法 描述 public void close()throws IOException 关闭输出流 public void flush()throws IOException 刷新缓冲区 public void write(byte[] b)throws IOException 将一个byte数组写入数据流 public void write(byte[] b,int off,int len)throws IOException 将一个指定范围的byte数组写入数据流 public abstract void write(int b)throws IOException 将一个字节数据写入数据流
此时使用FileOutputStream子类构造方法:
public FileOutputStream(File file)throws FileNotFoundException
import java. io. File ;
import java. io. FileOutputStream ;
import java. io. OutputStream ;
public class OutputStreamTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\outstream\\test.txt" ) ;
OutputStream out = new FileOutputStream ( file) ;
String str = "Hello World!!!" ;
byte b0[ ] = str. getBytes ( ) ;
out. write ( b0) ;
byte b1[ ] = str. getBytes ( ) ;
for ( int i = 0 ; i < b1. length; i++ ) {
out. write ( b1[ i] ) ;
}
out. close ( ) ;
}
}
追加新内容
可以通过FileOutputStream类的另外一个构造方法进行实例化表示文件的追加内容。
public FileOutputStream ( File file, boolean append) throws IOException
其中将append设置位true则表示在文件的末尾追加内容。
import java. io. File ;
import java. io. FileOutputStream ;
import java. io. OutputStream ;
public class OutputStreamTest1 {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\outstream\\test.txt" ) ;
OutputStream out = new FileOutputStream ( file, true ) ;
String str = "by bike!!!" ;
byte b[ ] = str. getBytes ( ) ;
for ( int i = 0 ; i < b. length; i++ ) {
out. write ( b[ i] ) ;
}
out. close ( ) ;
}
}
字节流输入:InputStream
public abstract class InputStream extends Object implements Closeable ;
方法 描述 public int available()throws IOException 可以取得输入文件的大小。 public void close()throws IOException 关闭输入流。 public abstreact int read()throws IOException 读入内容,以数字的方式读取。 public int read(byte[] b)throws IOException 将内容读到byte数组中,同时返回读入的个数。
import java. io. File ;
import java. io. FileInputStream ;
import java. io. InputStream ;
public class InputStreamTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\outstream\\test.txt" ) ;
InputStream in = new FileInputStream ( file) ;
byte b[ ] = new byte [ 1024 ] ;
int len = in. read ( b) ;
in. close ( ) ;
System . out. println ( "读取数据的长度:" + len) ;
System . out. println ( "内容为:" + new String ( b, 0 , len) ) ;
}
}
字符流
在程序中一个字符两个字节,那么Java提供了Reader和Writer两个专门操作字符流的类。
字符输出流:Writer
方法 描述 public abstract void close()throws IOException 关闭输入流。 public void write(String str)throws IOException 将字符串输出。 public void write(char[] cubf)throws IOException 将字符数组输出。 public abstract void flush()throws IOException 强制性清空缓存。
import java. io. File ;
import java. io. FileWriter ;
import java. io. Writer ;
public class WriteTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\writeread\\test.txt" ) ;
Writer w = new FileWriter ( file) ;
String str = "Hello world!!!" ;
w. write ( str) ;
w. close ( ) ;
}
}
追加新内容:
import java. io. File ;
import java. io. FileWriter ;
import java. io. Writer ;
public class AddTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\writeread\\test.txt" ) ;
Writer out = new FileWriter ( file) ;
String str = "\r\nHello world!!!" ;
out. write ( str) ;
out. close ( ) ;
}
}
字符输入流:Reader
方法 描述 public abstract void close()throws IOException 关闭输入流。 public int read()throws IOException 读取单个字符。 public int read(char[] cbuf)throws IOEception 将内容读取到字符数组中,返回读入的长度。
import java. io. File ;
import java. io. FileReader ;
import java. io. Reader ;
public class ReadTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\writeread\\test.txt" ) ;
Reader reader = new FileReader ( file) ;
char [ ] c = new char [ 1024 ] ;
int len = reader. read ( c) ;
reader. close ( ) ;
System . out. println ( "内容为:" + new String ( c, 0 , len) ) ;
}
}
字节流与字符流的区别
字节流在操作时不会用到缓冲区,是文件本身直接操作的,而字符流在操作时使用了缓冲区。 使用字节流不关闭执行。- 字节流是直接操作文件本身的。 字符流操作时使用了缓冲区,而在关闭字符流时会强制性的将缓冲区中内容进行输出,但如果程序没有关闭,则缓冲区中的内容是无法输出的。 文件在硬盘或在传输时都是以字节的方式进行的,而字符是只有在内存中才会形成,字节流使用较广泛。
文件复制
将源文件中的内容全部读取到内存中,并一次性写入到目标文件中。 不将源文件中的内容全部读取出来,而是采用边读边写的方式。
import java. io. * ;
public class CopyTest {
public static void main ( String [ ] args) {
if ( args. length!= 2 ) {
System . out. println ( "输入的参数不对。" ) ;
System . out. println ( "例如:Java copy 源文件路径 目标文件路径" ) ;
System . exit ( 1 ) ;
}
File file1 = new File ( args[ 0 ] ) ;
File file2 = new File ( args[ 1 ] ) ;
if ( ! file1. exists ( ) ) {
System . out. println ( "源文件不存在。" ) ;
System . exit ( 1 ) ;
}
InputStream input = null ;
OutputStream output = null ;
try {
input = new FileInputStream ( file1) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
}
try {
output = new FileOutputStream ( file2) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
}
if ( input != null && output!= null ) {
int temp= 0 ;
try {
while ( ( temp = input. read ( ) ) != - 1 ) {
output. write ( temp) ;
}
System . out. println ( "复制完成!" ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
System . out. println ( "复制失败!" ) ;
}
try {
input. close ( ) ;
output. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
转换流–OutputStreamWriter类和InputStreamReader类
OutputStreamWriter类是Writer类的子类,将输入的字符流变为字节流,即将一个字符流的输出对象变为字节流的输出对象。 InputStreamReader类是Reader类的子类,将输入的字节流变为字符流,即将一个字节流的输入对象变为字符流的输入对象。 将字节输出流变为字符输出流:
import java. io. File ;
import java. io. FileOutputStream ;
import java. io. OutputStreamWriter ;
import java. io. Writer ;
public class OutputStreamWriterTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\oswandisr\\test.txt" ) ;
Writer out = new OutputStreamWriter ( new FileOutputStream ( file) ) ;
out. write ( "hello world" ) ;
out. close ( ) ;
}
}
import java. io. File ;
import java. io. FileInputStream ;
import java. io. InputStreamReader ;
import java. io. Reader ;
public class InputStreamReaderTest {
public static void main ( String [ ] args) throws Exception {
File file = new File ( "E:\\daima\\java\\IO\\src\\oswandisr\\test.txt" ) ;
Reader reader = new InputStreamReader ( new FileInputStream ( file) ) ;
char c[ ] = new char [ 1024 ] ;
int len = reader. read ( c) ;
reader. close ( ) ;
System . out. println ( new String ( c, 0 , len) ) ;
}
内容操作流
之前的操作都是从文件中来的,我们也可以将输入和输出位置设置在内存上,这时候就要用到ByteArrayInputStream、ByteArrayOutputStream来完成内存的输入和输出功能。 ByteArrayInputStream类的主要方法:
方法 描述 public ByteArrayInputStream(byte[] buf) 将全部的内容写入内存中。 public ByteArrayInputStream(byte[] buf,int offest,int length) 将指定范围内的内容写入到内存中。
ByteArrayOutputStream类的主要方法:
方法 描述 public ByteArrayOutputStream() 创建对象。 public void write(int b) 将内容从内存中取出。
import java. io. ByteArrayInputStream ;
import java. io. ByteArrayOutputStream ;
import java. io. IOException ;
public class ByteArrayTest {
public static void main ( String [ ] args) {
String str = "HELLO WORLD" ;
ByteArrayInputStream bis = new ByteArrayInputStream ( str. getBytes ( ) ) ;
ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ;
int temp = 0 ;
while ( ( temp = bis. read ( ) ) != - 1 ) {
char c = ( char ) temp;
bos. write ( Character . toLowerCase ( c) ) ;
}
String newStr = bos. toString ( ) ;
try {
bis. close ( ) ;
bos. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
System . out. println ( newStr) ;
}
}
管道流
管道流主要作用是可以进行两个线程之间的通信。要连接两个输入输出区必须使用。 管道流分为管道输出流(PipedOutputStream)和管道输入流(PipedInputStream)
import java. io. IOException ;
import java. io. PipedInputStream ;
import java. io. PipedOutputStream ;
class Send implements Runnable {
private PipedOutputStream pos = null ;
public Send ( ) {
this . pos = new PipedOutputStream ( ) ;
}
@Override
public void run ( ) {
String str = "hello world!!!" ;
try {
this . pos. write ( str. getBytes ( ) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
this . pos. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
public PipedOutputStream getPos ( ) {
return pos;
}
}
class Receive implements Runnable {
private PipedInputStream pis = null ;
public Receive ( ) {
this . pis = new PipedInputStream ( ) ;
}
@Override
public void run ( ) {
byte b[ ] = new byte [ 1024 ] ;
int len = 0 ;
try {
len = this . pis. read ( b) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
this . pis. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
System . out. println ( "接收内容为:" + new String ( b, 0 , len) ) ;
}
public PipedInputStream getPis ( ) {
return pis;
}
}
public class PipedTest {
public static void main ( String [ ] args) {
Send send = new Send ( ) ;
Receive receive = new Receive ( ) ;
try {
send. getPos ( ) . connect ( receive. getPis ( ) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
new Thread ( send) . start ( ) ;
new Thread ( receive) . start ( ) ;
}
}
打印流
打印流基本操作
在整个IO中,打印流是输出信息最方便的类,主要包含字节打印流和字符打印流,可以打印任何的数据类型,这里主要看Print Stream类。 PrintStream类的常用方法:
方法 描述 public PrintStream(File file)throws FileNotFoundException 通过一个File对象实例化PrintStream类。 public PrintStream(OutputStream) 接收OutputStream对象,实例化PrintStream类。 public PrintStream printf(Local l,String format,Object…args) 根据指定的Locale格式化输出。 public PrintStream printf(String format,Object…args) 根据本地环境格式化输出。 public void print(boolean b) 此方法被重载多次,输出任意数据。 public void println(boolean b) 此方法被重载多次,输出任意数据后换行。
import java. io. File ;
import java. io. FileOutputStream ;
import java. io. PrintStream ;
public class PrintTest {
public static void main ( String [ ] args) throws Exception {
PrintStream ps = new PrintStream ( new FileOutputStream ( new File ( "E:\\daima\\java\\IO\\src\\printstream\\test.txt" ) ) ) ;
ps. print ( "hello" ) ;
ps. println ( "world" ) ;
ps. print ( "1+1=" + 2 ) ;
ps. close ( ) ;
}
}
使用打印流进行格式化
格式化输出的方式可以用printf()方法实现。 格式化输出:
字符 描述 %s 表示内容为字符串 %d 表示内容为整数 %f 表示内容为小数 %c 表示内容为字符
import java. io. File ;
import java. io. FileOutputStream ;
import java. io. PrintStream ;
public class PrintTest1 {
public static void main ( String [ ] args) throws Exception {
PrintStream ps = new PrintStream ( new FileOutputStream ( new File ( "E:\\daima\\java\\IO\\src\\printstream\\test.txt" ) ) ) ;
String name = "张三" ;
int age = 30 ;
float score = 90.5f ;
char sex = 'M' ;
ps. printf ( "姓名: %s;年龄: %d;成绩: %f;性别: %c" , name, age, score, sex) ;
ps. close ( ) ;
}
}