Java基础--读写文件

时间:2023-03-09 20:36:15
Java基础--读写文件

Java读写文件需要注意异常的处理,下面是一个例子

写文件

 public class WriteFile {

     public static void write(String file, String text){
try{
PrintWriter out = new PrintWriter(new File(file).getAbsoluteFile());
try{
out.print(text);
}finally{
out.close();
}
}catch(IOException e){
throw new RuntimeException(e);
}
} public static void main(String[] args) throws IOException{
String file = "test.txt";
//print current path
System.out.println(new File("").getAbsolutePath()); String context = "i am context, 1234567890!@#$%^&*()";
write(file, context);
} }

读文件

public class ReadFile {

    private static BufferedReader in;

    private static void openFile(String fname) throws Exception {
try {
in = new BufferedReader(new FileReader(fname));
} catch (FileNotFoundException e) {
// can not find file, not opened so no close
throw e;
} catch (Exception e) {
try {
// maybe opened, try to close
in.close();
} catch (IOException e2) {
// close failed, rare
// exception chain
// throw e2;
}
throw e;
} finally {
// empty, close can not be here
}
} public static String readFromFile(String fpath) throws Exception { openFile(fpath); StringBuffer sbf = new StringBuffer();
String s; try {
while ((s = in.readLine()) != null) {
sbf.append(s);
}
} catch (Exception e) {
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
throw e;
}
} return sbf.toString();
} public static void main(String[] args) throws Exception {
String str = readFromFile("test.txt");
System.out.println(str);
} }

end