?? filemanager.java
字號:
package base.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class FileManager {
public static final String LAST_CHAR="\n";
//寫文件 參數(絕對路徑,內容,是否創建,是否追加)
public static void write(String path, String content,boolean isCreate,boolean isAppend) {
try {
//判斷路徑是否存在
File file=new File(getShortPath(path));
if(!file.exists()){
if(isCreate)
file.mkdir();
else
throw new java.io.FileNotFoundException(path);
}
//如果是否存在文件,是否向后追加
File file1=new File(path);
if(!file1.exists()&&!isCreate){
throw new java.io.FileNotFoundException(path);
}
if(file1.exists()&&isAppend){
content=read(path)+content;
}
//開始寫文件
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
String array[] = content.split(LAST_CHAR);
for (int i = 0; i < array.length; i++) {
bw.write(array[i]);
bw.newLine();
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 寫文件 參數(絕對路徑,內容(集合),是否創建,是否追加)
public static void write(String path, List list,boolean isCreate,boolean isAppend) {
StringBuffer buffer=new StringBuffer();
for(Object obj:list){
buffer.append(obj+"\n");
}
write(path,buffer.toString(),isCreate,isAppend);
}
// 讀日志,根據傳進來的時間
public static String read(String path) throws FileNotFoundException {
File file=new File(path);
//判斷要讀取的文件是否存在
if(!file.exists()){
throw new java.io.FileNotFoundException(path);
}
StringBuffer result = new StringBuffer();
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String temp = null;
do {
temp = br.readLine();
if (temp != null){
result.append(temp+LAST_CHAR);
}
} while (temp != null);
fr.close();
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return result.toString().replaceAll(LAST_CHAR+LAST_CHAR,LAST_CHAR);
}
//獲取不帶路徑的文件名(兩種方法)
public static String getShortName(String path,boolean isMySelf){
return isMySelf?path.substring(path.lastIndexOf("\\")+1,path.length()): new File(path).getName();
}
public static String getExtendName(String path)
{
return (path.substring(path.lastIndexOf(".")+1,path.length())).toLowerCase();
}
//獲取不帶文件名的路徑
public static String getShortPath(String path){
return path.substring(0,path.lastIndexOf("\\")+1);
}
public static void main(String args[]){
try {
System.out.println("文件夾路徑:"+getShortPath("C:\\temp\\a.txt"));
System.out.println("文件名1:"+getShortName("C:\\temp\\a.txt",false));
System.out.println("文件名2:"+getShortName("C:\\temp\\a.txt",true));
System.out.println("擴展名:"+getExtendName("C:\\temp\\a.txt"));
write("C:\\temp\\a.txt", "大家好,我正在學習Java\n請多多指教",true,true);
System.out.print(read("C:\\temp\\a.txt"));
} catch (FileNotFoundException e) {
System.out.println("文件不存在!!!");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -