这次相比较上次而言 ,多了一个文本文件的读写,和一些大数的限制。通过这次作业,我复习了文本文件的读写,并且强化了自己的逻辑能力。虽然自己没能独立完成这次代码的编写,但是通过参考别人的代码自己弄懂了这个题目,收获很大。参考代码如下:
public static int[] toArrayByFileReader1(String name) {
// 使用ArrayList来存储每行读取到的字符串
File file = new File(name);
judeFileExists(file);
ArrayList<String> arrayList = new ArrayList<>();
try {
FileReader fr = new FileReader(name);
BufferedReader bf = new BufferedReader(fr);
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null) {
arrayList.add(str);
}
bf.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对ArrayList中存储的字符串进行处理
int length = arrayList.size();
int[] array = new int[length];
for (int i = 0; i < length; i++) {
String s = arrayList.get(i);
array[i] = Integer.parseInt(s);
}
// 返回数组
return array;
}
public static void judeFileExists(File file) {
if (file.exists()) {
System.out.println("文件存在!");
}
else {
System.out.println("文件不存在!");
System.exit(0);
// try {
// file.createNewFile();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
public static int[] toArrayByFileReader1(String name) {
// 使用ArrayList来存储每行读取到的字符串
File file = new File(name);
judeFileExists(file);
ArrayList<String> arrayList = new ArrayList<>();
try {
FileReader fr = new FileReader(name);
BufferedReader bf = new BufferedReader(fr);
String str;
// 按行读取字符串
while ((str = bf.readLine()) != null) {
arrayList.add(str);
}
bf.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对ArrayList中存储的字符串进行处理
int length = arrayList.size();
int[] array = new int[length];
for (int i = 0; i < length; i++) {
String s = arrayList.get(i);
array[i] = Integer.parseInt(s);
}
// 返回数组
return array;
}
public static void judeFileExists(File file) {
if (file.exists()) {
System.out.println("文件存在!");
}
else {
System.out.println("文件不存在!");
System.exit(0);
// try {
// file.createNewFile();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}