IO
Java中使用IO(输入输出)来读取和写入,读写设备上的数据、硬盘文件、内存、键盘…,根据数据的走向可分为输入流和输出流,这个走向是以内存为基准的,即往内存中读数据是输入流,从内存中往外写是输出流。
Input(输入):是一个从外界进入到程序的方向,通常我们需要“读取”外界的数据时,使用输入。所以输入是用来读取数据的
Output(输出):是一个从程序发送到外界的方向,通常我们需要“写出”数据到外界时,使用输出。所以输出是用来写出数据的
InputStream 是所有字节输入流的父类,其定义了基础的读取方法,如下:
- int read():读取一个字节,以int形式返回,该int值的“低8位”有效,若返回值为-1则表示EOF
- int read(byte[] d):尝试最多读取给定数组length个字节并存入该数组,返回值为实际读取到的字节量
OutputStream 是所有字节输出流的父类,其定义了基础的写出方法,如下:
- void write(int d):写出一个字节,写的是给定的int的“低8位”
- void write(byte[] d):将给定的字节数组中的所有字节全部写出
实例
public static void readFile(String pathName) {
try (
FileInputStream input = new FileInputStream(new File(pathName));
){
byte[] b = new byte[1024];
int len = 0 ;
StringBuffer sb = new StringBuffer();
while( (len=input.read(b)) != -1) {
sb.append(new String(b,0,len));
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeFile(String pathName,String str) {
try (
//加上 true 为在文件中追加内容,默认为False
FileOutputStream output = new FileOutputStream(new File(pathName),true);
){
output.write(str.getBytes());
} catch (Exception e) {
// TODO: handle exception
}
}
public static void copyFile(String sourcePath,String targetPath) {
long begin = System.currentTimeMillis();
try (
FileInputStream input = new FileInputStream(new File(sourcePath));
FileOutputStream output = new FileOutputStream(new File(targetPath));
){
int len = 0 ;
byte[] b = new byte[1024];
while( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
} catch (Exception e) {
}
System.out.println("文件复制耗时为:"+(System.currentTimeMillis() - begin)+"毫秒");
}
public static void dateMutualString() throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
String date = "2018-04-25 10:05:21";
long time = new Date().getTime();
System.out.println(simpleDateFormat.format(time).getClass());
System.out.println(simpleDateFormat.parse(date).getClass());
}
var foo = 'bar';