文件IO流:通过数据流、序列化和文件系统提供系统输入和输出。
系统输入
用到的四个类有如下:
File:文件类,用于创建、修改、删除一个文件。File file = new File(path)定义了一个file的文件对象,常用的方法有:
isFile():检查path表示的文件是否是一个标准文件
exists():判断抽象路径名表示的文件或目录是否存在InputStream:public abstract class InputStream extends Object implements Closeable
此抽象类是指字节输入流的所有类的超类。抽象类不能直接创建对象,创建对象时需要其实现类FileInputStream创建,创建一个字节输入流的对象。InputStreamReader:是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。可以创建使用默认字符集或者指定字符集的对象。
BufferStreamReader:将InputStreamReader生成字符流缓冲输入。
实现代码如下:
package com.company.utils;
import java.io.*;
/**
* Created by viga on 2017/8/6.
*/
public class FileUtil {
//文件读取,将文件中的内容以字符串类型返回
public static String fileRead(String path){
File file = new File(path);//定义一个文件
String info = "";
if(file.isFile() && file.exists()){//判断文件是否是标准文件并且是否存在
try {
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
try {
info = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
System.out.println("文件不存在!");
}
return info;
}
}