9.1文件操作
2017-04-18 本文已影响75人
孔垂云
java的文件操作还是非常强大的,这里主要说明几点,后面有一个详细的文件读写例子。
1、文件读写一定要确保文件打开后要关闭,而且关闭方法要写在finally中,java8出现的闭包操作也可以实现。
2、文件读写一定要明确文件编码方式,是UTF-8还是GBK,不然肯定会出错
3、文件读写分大文件读写和小文件读写,大文件读写需要用到buffer,即缓冲,小文件就无所谓了
4、java读写文件时,文件存储路径不要带中文,java对中文的支持还是差一些。
代码参照com.critc.FileReadWriteTest
public class FileReadWriteTest {
/**
* 创建文件夹
*
* @throws Exception
*/
public void createDir() throws Exception {
String path = "D:" + File.separator + "dir";
File file = new File("D:\\dir");
if (!file.exists())
file.mkdir();
}
/**
* 创建文件
*
* @throws Exception
*/
public void createFile() throws Exception {
File file = new File("D:\\dir\\test.txt");
if (!file.exists())
file.createNewFile();
}
/**
* 删除文件
*/
public void deleteFile() {
File file = new File("D:\\dir\\test.txt");
file.deleteOnExit();
if (file.exists())
file.delete();
}
/**
* 读取文件列表
*
* @return
*/
public List<String> readFile() {
String path = "D:\\dir\\test.txt";
File file = new File(path);
List<String> list = new ArrayList<String>();
BufferedReader reader = null;
try {
if (file.exists()) {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
list.add(tempString);
}
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return list;
}
/**
* 写文件
*/
public void writeFile() {
String path = "D:\\dir\\test.txt";
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(path);
OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream, "GBK");
String fileContent = "测试\r\n20160720\r\n";
osw.write(fileContent);
osw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
FileReadWriteTest fileReadWrite = new FileReadWriteTest();
fileReadWrite.createDir();
fileReadWrite.createFile();
// fileReadWrite.deleteFile();
fileReadWrite.writeFile();
List<String> list = fileReadWrite.readFile();
for (String str : list) {
System.out.println("文件内容:" + str);
}
}
}