本文主要讲述:文件读取和写入工具类
Java IO流共涉及40多个类,但基类只有四个:
InputStream / Reader :所有输入流的基类,前者是字节输入流,后者是字符输 入流
OutputStream / Writer :所有输出流的基类,前者是字节输出流,后者是字符输出 流
一、BufferedReader整行读取
public static String readFile(String filename) {
File file = new File(filename);
InputStream is = null;
Reader reader = null;
BufferedReader bufferedReader = null;
StringBuilder result = new StringBuilder();
try {
is = new FileInputStream(file);
reader = new InputStreamReader(is);
bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
result.append("\r\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != bufferedReader)
bufferedReader.close();
if (null != reader)
reader.close();
if (null != is)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
二、InputStream字节读取
public static String readFileByChar(String filename) {
File file = new File(filename);
InputStream is = null;
Reader isr = null;
StringBuilder result = new StringBuilder();
try {
is = new FileInputStream(file);
isr = new InputStreamReader(is);
int index;
while (-1 != (index = isr.read())) {
result.append((char) index);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
if (null != isr)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
三、BufferedWriter写文件
public static void writeByBuffered(String filename, String context) {
File file = new File(filename);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
bw.write(context);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bw) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != osw) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四、OutputStreamWriter写文件
public static void write(String filename, String context) {
File file = new File(filename);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos);
osw.write(context);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
本文所有代码都是亲测可试,可直接拿来使用的。
由于代码排版格式及手机尺寸有限,使用电脑观看此文效果更佳,感谢您的阅读!