import java.io.File;
import java.io.IOException;
/**
* 创建文件
*
* @author chendongj
*
*/
public class CreateFile {
public void createFile(String path) {
File aFile = new File(path);
try {
if (aFile.exists()) {
aFile.delete();
aFile.createNewFile();
System.out.println("创建文件成功!");
} else {
aFile.createNewFile();
System.out.println("创建文件成功!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CreateFile cf = new CreateFile();
cf.createFile("E:/test.txt");
}
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author 向文件写内容
*
*/
public class Write2File {
public void write2File(String path) {
try {
File aFile = new File(path);
FileWriter out = new FileWriter(aFile, true);
out.write("11111111");
out.flush();
System.out.println("写入成功!");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 从文件中读内容
*
* @author chendongj
*
*/
public class ReadFromFile {
public void readFromFile(String path) {
System.out.println("读取内容:");
try {
FileReader fr = new FileReader(new File(path));
while (fr.read() != -1) {
System.out.print((char) fr.read());
}
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TestFile {
/**
* 测试文件创建 读写
*/
public static void main(String[] args) {
String path = "E:/test.txt";
CreateFile createFile = new CreateFile();
createFile.createFile(path);
Write2File w2f = new Write2File();
w2f.write2File(path);
ReadFromFile rff = new ReadFromFile();
rff.readFromFile(path);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有