Java的文件读取使用File类, 进行读取:
exists(): 判断文件存在与否;
createNewFile(): 创建新的文件;
isDirectory(): 是否是文件夹;
FileOutputStream: 写文件;
FileInputStream: 读文件;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class JavaTest {
public static void main(String args[]) {
FtDebug.setFileName("test.txt");
FtDebug.init();
FtDebug.writeLog("this is the first log");
FtDebug.close();
System.out.println(FtDebug.getContent("test.txt"));
}
public static class Log {
public static void e(String tag, String log) {
System.out.println(log);
}
}
public static class FtDebug {
private static final String TAG = "DEBUG";
private static String debugFileName = null;
private static String debugFileBakName = null;
private static File fileDebug = null;
private static FileOutputStream fosDebug = null;
public static void setFileName(String name) {
debugFileName = name;
debugFileBakName = debugFileName + "_bak";
}
public static boolean init() {
if (debugFileName == null) {
return false;
}
if ((fileDebug != null) && fileDebug.exists()) {
fileDebug.renameTo(new File(debugFileBakName)); // move file to backup file, delete file
fileDebug.delete();
}
fileDebug = new File(debugFileName);
try {
if (fileDebug.exists()) {
fileDebug.renameTo(new File(debugFileBakName)); // move file to backup file, delete file
fileDebug.delete();
}
if (!fileDebug.createNewFile()) {
Log.e(TAG, "create debug file failed!");
return false;
}
fosDebug = new FileOutputStream(fileDebug);
if (fosDebug == null) {
Log.e(TAG, "create file output stream failed!");
return false;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "create debug file exception!");
return false;
}
return true;
}
public static void addTimeStamp() {
}
public static void writeLog(String log) {
try {
String timeStamp = String.format("<%d>", System.currentTimeMillis());
fosDebug.write(timeStamp.getBytes()); // add time stamp
fosDebug.write(log.getBytes());
fosDebug.write(new byte[]{'\r', '\n'});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "write file output stream exception!");
}
}
public static void close() {
try {
fosDebug.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "close file output stream exception!");
}
}
public static String getContent(String fileName) {
File file = new File(fileName);
StringBuffer content = new StringBuffer();
if (!file.exists()) {
return "";
}
try {
FileInputStream fis = new FileInputStream(file);
int character;
while ( (character = fis.read()) != -1) {
content.append((char)character);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content.toString();
}
}
}