题目
在当前目录创建一个文件a.dat,向该文件写入1-10的平方根,并读出这10个数,显示在屏幕上。
程序流程图
参考代码
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @author MingxiangWen
*/
public class FileHomework {
public FileHomework() {
try {
// 1. 创建文件并写入数据
createFile();
// 2. 打开文件并显示
openFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void openFile() throws FileNotFoundException {
File file = new File("a.dat");
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
while ((s = br.readLine()) != null) {
result.append(System.lineSeparator() + s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result.toString());
}
public void createFile() throws Exception {
File file = new File(".", "a.dat");
if (file.exists()){
file.delete();
}
file.createNewFile();
// 3.存放计算结果
String str = "";
for (int i = 1; i < 11; i++) {
str += "" + Math.sqrt(i) + System.lineSeparator();
}
// 3. 创建文件输入流
FileOutputStream fileOutputStream = new FileOutputStream(file);
// 4.将运算结果转化为字节数组
byte[] b = str.getBytes(StandardCharsets.UTF_8);
fileOutputStream.write(b);
// 5.关闭流
fileOutputStream.close();
}
public static void main(String[] args) {
new FileHomework();
}
}
运行结果
说明
个人能力有限,仅供参考,共同学习!