- File类 用于操作文件或目录,若要访问文件内容本身,则需要使用输入/输出流。
- 文件过滤器 在File类的list()方法中可以接受一个FileNameFilter参数,通过该参数值列出符合条件的文件。
import java.io.File;
import java.io.FilenameFilter;
public class FilenameFilterTest
{
public static void main(String[] args)
{
File file = new File(".");
String[] nameList = file.list(new MyFilenameFilter());
for(String name : nameList)
{
System.out.println(name);
}
}
}
// 实现自己的FilenameFilter实现类
class MyFilenameFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
// 如果文件名以.java结尾,或者文件对应一个路径,返回true
return name.endsWith(".java")
|| new File(name).isDirectory();
}
}
- I/O流 从内存的角度考虑,数据从内存到硬盘,称输出流;数据从服务器通过网络流向客户端,服务器端使用输出流,客户端使用输入流。字节流主要由InputStream和OutputStream作为基类,字符流主要由Reader和Writer作为基类。
InputStream常用方法:
int read():读取单个字节,返回字节数据
int read(byte[] b):最多读取b.length()个字节数据
Reader常用方法:
int read():读取单个字符,返回字符数据
int read(char[] b):最多读取b.length()个字符数据
OutputStream,Writer常用方法:
void write(int c);将指定的字节/字符输出到输出流中
void write(byte[]/char[] buf);将字节数组/字符数组中的数据输出到指定输出流中
Writer可用字符串代替字符数组,可用以下方法:
void write(String str);将str字符串里包含的字符输出到指定的输出流中
使用FileInputStream读文件:
public class FileInputStreamTest
{
public static void main(String[] args) throws IOException
{
// 创建字节输入流
FileInputStream fis = new FileInputStream(
"FileInputStreamTest.java");
// 创建一个长度为1024的“竹筒”
byte[] bbuf = new byte[1024];
// 用于保存实际读取的字节数
int hasRead = 0;
// 使用循环来重复“取水”过程
while ((hasRead = fis.read(bbuf)) > 0 )
{
// 取出“竹筒”中水滴(字节),将字节数组转换成字符串输入!
System.out.print(new String(bbuf , 0 , hasRead ));
}
// 关闭文件输入流,放在finally块里更安全
fis.close();
}
}
使用FileReader读文件
public class FileReaderTest
{
public static void main(String[] args)
{
try(
// 创建字符输入流
FileReader fr = new FileReader("FileReaderTest.java"))
{
// 创建一个长度为32的“竹筒”
char[] cbuf = new char[32];
// 用于保存实际读取的字符数
int hasRead = 0;
// 使用循环来重复“取水”过程
while ((hasRead = fr.read(cbuf)) > 0 )
{
// 取出“竹筒”中水滴(字符),将字符数组转换成字符串输入!
System.out.print(new String(cbuf , 0 , hasRead));
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
使用FileOutputStream复制文件
public class FileOutputStreamTest
{
public static void main(String[] args)
{
try(
// 创建字节输入流
FileInputStream fis = new FileInputStream(
"FileOutputStreamTest.java");
// 创建字节输出流
FileOutputStream fos = new FileOutputStream("newFile.txt"))
{
byte[] bbuf = new byte[32];
int hasRead = 0;
// 循环从输入流中取出数据
while ((hasRead = fis.read(bbuf)) > 0 )
{
// 每读取一次,即写入文件输出流,读了多少,就写多少。
fos.write(bbuf , 0 , hasRead);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
使用FileWriter复制文件:
public class FileWriterTest
{
public static void main(String[] args)
{
try(
FileWriter fw = new FileWriter("poem.txt"))
{
fw.write("锦瑟 - 李商隐\r\n");
fw.write("锦瑟无端五十弦,一弦一柱思华年。\r\n");
fw.write("庄生晓梦迷蝴蝶,望帝春心托杜鹃。\r\n");
fw.write("沧海月明珠有泪,蓝田日暖玉生烟。\r\n");
fw.write("此情可待成追忆,只是当时已惘然。\r\n");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}