import java.io.FileInputStream;
import java.io.FileOutputStream;
//import org.apache.commons.lang.CharEncoding;
/**
* file讀寫工具類
*/
public class FileReadAndWrite {
public static void main(String[] args) {
// FileReadAndWrite.read("E:\\java-study\\src\\com\\streamTest\\fis2.txt");
// FileReadAndWrite.write("E:\\java-study\\src\\com\\streamTest\\fos.txt", "linge加油", WriteType.ADD);
FileReadAndWrite.copy("C:\\Users\\lucklin\\Desktop\\abc.png", "E:\\java-study\\src\\com\\streamTest\\abc.png");
}
/**
* @description 讀取文件內容
* @param path 文件路徑
*/
static String read(String path) {
String res = null;
try {
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[1024];
int len = 0;
while ((len = fis.read(b)) != -1) {
res = new String(b,0, len);
}
fis.close();
} catch(Exception e) {
System.out.println("文件讀取異常:"+e.getMessage());
}
return res;
}
/**
* @description 寫入文件內容
* @param path 文件路徑
* @param content 寫入內容
*/
static void write(String path, String content) {
try {
//new FileOutputStream在文件不存在的情況下會默認創建,所以雖然會拋出不存在異常但是不會阻塞後續執行,前提path要正確
FileOutputStream fos = new FileOutputStream(path);
byte[] b = content.getBytes();
// System.out.println(b.length);
// fos.write(b,0, b.length);//寫入內存
fos.write(b);//寫入內存
fos.flush();//寫入硬盤
fos.close();
System.out.println("寫入成功");
} catch (Exception e) {
System.out.println("文件寫入異常:"+e.getMessage());
}
}
/**
* @description 寫入文件內容
* @param path 文件路徑
* @param content 寫入內容
* @param type 寫入方式
*/
static void write(String path, String content, WriteType type) {
String oldContent = read(path);
content = oldContent != null && type.equals(WriteType.ADD) ? oldContent + content : content;
write(path, content);
}
/**
* @description 複製文件
* @param source 文件路徑
* @param target 目標文件路徑
*/
// static void copy(String source, String target) {//new String()和String.getBytes的編碼問題有時間再研究
// String content = read(source);
// if(content != null) write(target, content);
// }
static void copy(String source, String target) {
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target);
byte[] b = new byte[1024];
int len = 0;
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.flush();
fis.close();
fos.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
enum WriteType{
// ADD,
// REPLACE
ADD("add", "追加寫入"),
REPLACE("replace", "覆蓋寫入");
private final String TYPE;
private final String DESC;
WriteType(String type, String desc) {
TYPE = type;
DESC = desc;
}
}