我发现python真是一门胶水语言,语法简介,代码量很少。举个例子,就拿io操作例子吧,Java需要大量的代码,异常判断,python两句话搞定。
python
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
#write file
with open("test.txt","wt") as out_file:
out_file.write("测试写入文件")
#read file
with open("test.txt","rt") as in_file:
text = in_file.read()
print(text)
java
package org.java.base.algorithm;
import java.io.*;
/**
* @ClassName IOTest
* @Description TODO
* @Author liuhaihua
* @Date 2021/7/28 21:45
* @Version 1.0
*/
public class IOTest {
public static void main(String[] args){
String filepath ="/Users/liuhaihua/logs/11.txt";
String msg ="你好,这是一个测试";
writeFile(filepath,msg);
System.out.println(readFile(filepath));
}
/**
* 写文件
*/
public static void writeFile(String filepath,String msg){
try {
File file = new File(filepath);
if (file.exists()) {//存在
file.delete();//删除再建
file.createNewFile();
} else {
file.createNewFile();//不存在直接创建
}
FileWriter fw = new FileWriter(file);//文件写IO
fw.write(msg);
fw.flush();
fw.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 读文件
*/
public static String readFile(String filepath){
String temp="";
String str ="";
try {
File file = new File(filepath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);//文件读IO
while((temp = br.readLine())!=null){//读到结束为止
str += (temp+"\n");
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8