1. 创建文件
使用了File类中的createrNewFile方法。
public static boolean createFile(String filename){try{File file = new File(filename);file.createNewFile();return true;} catch (IOException e) {e.printStackTrace();return false;}}
查阅文档可知,若文件不存在,就创建新的文件,返回true,若文件已经存在,返回false。
不过此处我们只关注有这个文件就行,别的不管,因此忽略返回值。
核心:对于io方面的类File,以及Java中的各种功能类,我们需要理解的是它如何工作,如何使用,其他的可以不必深究,我们可以先当成黑盒子用,不过,等你使用熟练了,还是得深入理解原理,这样才能成长。
2. 写入二维数组到文件
读写文件的关键点
- 打开文件
- 读/写
- 关闭文件!
就像你在Windows上经常操作的那样,打开,写入,保存,关闭。
用程序执行,其实是一样的,只不过Windows可视化了而已,本质一样的!
public static boolean writeToFile(String filename, int[][] Array){try {FileWriter fileWriter = new FileWriter(filename);for(int arr[]:Array){for(int value:arr){fileWriter.write(value + "\t");}fileWriter.write("\n");}fileWriter.close();return true;} catch (IOException e) {e.printStackTrace();return false;}}
更多细节查阅官方文档即可。
3. 读取文件并转换为二维数组
这里使用的是Scanner的读取功能,完成文件的读取,并将其存到二维数组中。
public static int[][] readFile(String filename) {int[][] arr = new int[4][3];try {File file = new File(filename);Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {for (int i = 0; i < arr.length; i++) {String[] line = scanner.nextLine().split("\t");for (int j = 0; j < line.length; j++) {arr[i][j] = Integer.parseInt(line[j]);}}}scanner.close();} catch (FileNotFoundException e) {e.printStackTrace();}return arr;}
此处,需要注意,这里是行列已知,如果未知,需要使用动态二维数组来完成读取。
此外,它读取的是字节,如果想要快一点,或许你可以试试加个Buffer!