盒子
盒子
文章目录
  1. FilenameFilter
  2. 输入
    1. 读取文件到缓存
    2. 读取字符串到内存
    3. 读取字节到内存
  3. 输出
    1. 写内容到文件
  4. 存储和恢复数据
  5. 随机存储访问数据
  6. 读取二进制文件
  7. 标准I/O
    1. 将System.out转换成PrintWriter
    2. 重定向
  8. 新I/O
  9. 补充

Java的I/O系统

FilenameFilter

文件过滤器,获取指定的文件
dd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
public class Filenamer {
public static void main(String...args){
File path=new File(".");
String[] files;
if(args.length==0){
files=path.list();
}else{
files=path.list(new DirFilter(args[0]));
}
if(files==null){
return;
}
for(String file:files){
System.out.println("file:"+file);
}
}
}
class DirFilter implements FilenameFilter {
private Pattern pattern;
public DirFilter(String regex){
pattern=Pattern.compile(regex);
}
@Override
public boolean accept(File pathname,String name) {
return pattern.matcher(name).matches();
}
}

DirFilter重写了FilenameFilter的accept方法根据传入的正则判断出符合条件的文件名,符合返回true,不符合返回false

accept方法供list方法调用,list方法源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public String[] list(FilenameFilter filter) {
String names[] = list();
if ((names == null) || (filter == null)) {
return names;
}
List<String> v = new ArrayList<>();
for (int i = 0 ; i < names.length ; i++) {
if (filter.accept(this, names[i])) {
v.add(names[i]);
}
}
return v.toArray(new String[v.size()]);
}

输入

读取文件到缓存

1
2
3
4
BufferedReader in=new BufferedReader(new FileReader(fileName));
while((str=in.readLine())!=null){
strs.append(str);
}

读取字符串到内存

1
2
3
4
5
StringReader in=new StringReader(str);
//in。read返回字符的Ascall码,内容读取完则返回-1
while((c=in.read())!=-1){
System.out.println((char)c);
}

读取字节到内存

1
2
3
4
5
6
//new ByteArrayInputStream()将字节数组转换成字节流
DataInputStream in=new DataInputStream(new ByteArrayInputStream(str.getBytes());
//in.readByte()返回下一个字节,当已经到达末尾,会抛出EOFException异常
while(in.available()!=0){
System.out.println((char)in.readByte())
}

输出

写内容到文件

1
2
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
out.println(str);

存储和恢复数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try {
DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("test.txt")));
out.writeChar('c');
out.writeBoolean(true);
out.writeDouble(12.3222222);
out.writeUTF("str");
out.close();
DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
//注意读取有顺序区分
System.out.println(in.readChar()+" "+in.readBoolean()+" "+in.readDouble()+" "+in.readUTF());
in.close();
} catch (IOException e) {
e.printStackTrace();
}

c true 12.3222222 str

随机存储访问数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
String fileName="test.txt";
try {
RandomAccessFile out=new RandomAccessFile(fileName,"rw");
out.writeDouble(0.0);
out.writeDouble(0.1);
out.writeDouble(0.2);
out.writeDouble(0.3);
out.writeDouble(0.4);
out.close();
RandomAccessFile in=new RandomAccessFile(fileName,"rw");
System.out.println(in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" ");
//in.close();
out=new RandomAccessFile(fileName,"rw");
//一个double数值为8字节
out.seek(8);
out.writeDouble(1.0);
out.close();
//in=new RandomAccessFile(fileName,"r");
//回到开始位置,重新读取数据
in.seek(0);
System.out.println(in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" "+in.readDouble()+" ");
in.close();
}catch (IOException e){
e.printStackTrace();
}

0.0 0.1 0.2 0.3 0.4

0.0 1.0 0.2 0.3 0.4

读取二进制文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//传入File对象获得二进制数据
public static byte[] readByte(File file){
BufferedInputStream in=new BufferedInputStream(new FileInputStream(file));
try{
byte[] bytes=new byte[in.available()];
in.read(bytes);
return bytes;
}catch(IOException e){
e.printStackTrace();
}
}
//通过文件名新建File对象,然后调用第一个静态方法
public static byte[] readByte(String fileName){
return read(new File(fileName).getAbsoluteFile());
}

标准I/O

将System.out转换成PrintWriter

1
2
PrintWriter out=new PrintWriter(System.out,true);
out.println("str");
1
public PrintWriter(OutputStream out, boolean autoFlush)

System.out为PrintWriter,而PrintWriter又为OutputStream所有可作为第一个参数,第二个参数为是否自动清空功能,需要设为true,否则可能无法看到输出

重定向

输出重定向:

1
2
3
4
5
6
7
try{
PrintStream out=new PrintStream(new FileOutputStream("test.txt"));
System.setOut(out);
out.println("Hello world");
}catch (IOException e){
e.printStackTrace();
}

将Hello world重定向输出到test.txt文件中,而标准输出是将其输出到控制台

输入重定向:

1
2
3
4
5
6
7
8
9
10
try{
FileInputStream in=new FileInputStream("test.txt");
System.setIn(in);
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
System.out.println(scanner.nextLine());
}
}catch (IOException e){
e.printStackTrace();
}

Hello world

新I/O

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
try{
FileChannel channel=new FileOutputStream("test.txt").getChannel();
channel.write(ByteBuffer.wrap("FileOutputStream".getBytes()));
channel.close();
channel=new RandomAccessFile("test.txt","rw").getChannel();
//移动到末尾处以便追加内容
channel.position(channel.size());
channel.write(ByteBuffer.wrap("RandomAccessFile".getBytes()));
channel.close();
channel=new FileInputStream("test.txt").getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);
channel.read(buffer);
//让channel做好读取字节的准备
buffer.flip();
while(buffer.hasRemaining()){
System.out.println((char)buffer.get());
}
}catch (IOException e){
e.printStackTrace();
}

读写通过缓冲器由通道写出或读入,更快速高效

  • asCharBuffer
  • CharSet

    1
    2
    String encoding=System.getProperty("file.encoding");
    System.out.println(Chaset.forName(encoding).decode(buff));

    为字节缓冲器编码

    ByteBuffer

    1
    ByteBuffer.wrap("test".getBytes("UTF-16BE"));

    将”test”字符串转换成以”UTF-16BE”编码的字节封装到字节缓冲器中

    1
    System.out.println(buff.asCharSet());

    将字节缓冲区中的字节转换成字符集存入字符缓冲器中,输出该缓冲区会自动调用其toString方法

    CharBuffer

    补充

  • java获取当前路径的几种方法
  • 1
    2
    3
    4
    5
    6
    7
    8
    //1
    System.out.println(System.getProperty("user.dir"));
    //2
    File directory = new File("");
    try
        System.out.println(directory.getCanonicalPath());
        System.out.println(directory.getAbsolutePath());
    }catch(Exceptin e){}

  • 对于append,不能通过”\n”来实现换行,需要:
  • 1
    printStream.append(System.getProperty("line.separator"));
    支持一下
    扫一扫,支持Grooter
    • 微信扫一扫
    • 支付宝扫一扫