java.io => 裡面放了很多種處理檔案的工具和物件
File(fileName) => fileName: 檔案夾的路徑位置
這個物件可以去
import java.io.File;
public class Main {
public static void main(String[] args) {
String fileName = "C:\\Users\\Max\\IOfile";
String newName = "C:\\Users\\Max\\IOfile\\TestFolder";
File file = new File(fileName);
File file1 = new File(newName);
// 建立資料夾
file1.mkdirs();
// 讀取目錄
String[] arr = file.list();
for (String i: arr) {
System.out.println(i);
}
System.out.println("-------------");
// 刪除檔案
// file1.delete();
System.out.println("end");
}
}
import java.io.*;
public class Main {
public static void main(String[] args) {
String fileName = "C:\\Users\\IOfile\\text.txt";
read(fileName);
}
public static void read(String fileName){
FileReader fr = null;
try {
fr = new FileReader(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String tmp = null;
try {
while (((tmp = br.readLine()) != null)) {
System.out.println(tmp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String fileName = "C:\\Users\\Max\\IOfile\\text.txt";
write(fileName);
}
public static void write(String fileName){
List<String> list = new ArrayList<String>();
list.add("Java的I/O");
list.add("讀取檔案內容");
list.add("寫入檔案內容");
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
for (String s: list){
bw.write(s); // 寫入資料
bw.newLine(); // 新增一行
}
bw.flush(); // 把記憶體資料寫進去
} catch (IOException e) {
e.printStackTrace();
}
}
}