1. 程式人生 > >Java IO讀寫操作

Java IO讀寫操作

public class IOHandle {
    public static String readTxtFile(String filePath) {
        BufferedReader bre = null;
        try {
            String encoding = "GBK";
            String str;
            String phone = "";
            String out= "";
            File file = new File(filePath);
            //先判斷檔案是否存在
if (file.isFile() && file.exists()) { bre = new BufferedReader(new FileReader(file)); while ((str = bre.readLine()) != null) //判斷最後一行不存在,為空結束迴圈 { //逐行讀取 str=str.replace(" ",""); out
=out+str; } bre.close(); return out; }else{ System.out.println("找不到指定的檔案"); return "找不到指定的檔案"; } } catch (Exception e) { System.out.println("讀取檔案內容出錯"); e.printStackTrace(); return
"找不到指定的檔案"; } } public static void weriteTxtFile(String context,String filePath) { BufferedWriter bre = null; File file = new File(filePath); try { bre = new BufferedWriter(new FileWriter(file)); bre.write(context); bre.close(); } catch (IOException e) { e.printStackTrace(); } } }