JAVA IO
I/O即input/output 输入/输出,通常指数据在内部存储器和外部存储器或其他周边设备内进行输出.
字节流
程序使用字节流执行8位的输入(input)和输出(output).而所有字节流最小的单元为字节
1 2
| java.io.FileInputStream java.io.FileOutpuStream
|
将1.txt文件内容写入\覆盖到2.txt之中
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
| import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;
public class Demo { public static void main (String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("/home/sunli/1.txt"); out = new FileOutputStream("/home/sunli/2.txt"); int i; while((i = in.read()) !=-1) { out.write(i); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
|
字符流
字符流是以16位作为数据单元数据流中的最小数据单元就是单元字符,也就是Unicode每位即占2位字符
Writer
writer是所有输出字符流的父类.是一个抽象的类;
CharArrayWriter\StringWriter是两种基本介质流,分别想char\String中写入数据.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public void write(int c) throws IOException;
public void write(char cbuf[]) throws IOException
public abstract void write(char cbuf[],int off,int len) throws IOException
public void write(String str) throws IOException;
public void write(String str,int off,int len) throws IOException
|
读取文件内信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import java.io.File; import java.io.FileReader; import java.io.IOException;
public class Demo { public static void main (String args[]) throws IOException { FileReader reader = null; try { File readFile = new File("/home/sunli/1.txt"); reader = new FileReader(readFile); char [] byteArray = new char[(int) readFile.length()]; int size = reader.read(byteArray); System.out.println(new String(byteArray)); } catch (Exception e) { e.printStackTrace(); } finally { reader.close(); } } }
|
非流式部分
非流式部分主要包含一些辅助流式部分的类,如:SerializablePermission\File\RandomAccessFile\FileDescriptor
读取目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.io.*;
public class Demo { public static void main (String args[]) { String dir = "/home/"; File f = new File(dir); if(f.isDirectory()) { String s[] = f.list(); for (int i = 0; i <s.length;i++) { if(f.isDirectory()) { System.out.println("/" + s[i]); } } } } }
|
⬅️ Go back