Java讀寫文件

public static void readFile(String filePath) throws IOException {
    File file = new File(filePath);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String r = null;
    while ((r = br.readLine()) != null){
        System.out.println(r);
    }
}

public static void writeFile(String filePath) throws IOException {
    File file = new File(filePath);
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write("第一行的內容");
    //換行
    bw.newLine();
    bw.write("第二行的內容");
    //將數據寫入文件
    bw.flush();
    bw.close();
}

 另外,獲取classes目錄的方法:

非靜態函數:String resourcesPath = this.getClass().getResource("/").getPath();
靜態函數:String resourcesPath = 類名.class.getResource("/").getPath();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章