相信大家在学习各种编程语言的时候在学习文件操作时不想搜到那些繁琐的教学,这里直接上模板。
//文件读取
try {
File fp = new File("src\\P1\\txt\\" + fileName); //打开文件(文件地址用双斜线替换)
try {
FileInputStream file = new FileInputStream(fp); //输入流
byte[] bytes = new byte[file.available()];
int len;
while ((len = file.read(bytes)) != -1) { //从文件中读取数据
String str = new String(bytes, 0, len); //str即为储存文件内容的字符串
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (Exception e) {
e.printStackTrace();
}
//文件写入
try {
File fp = new File("src\\P1\\txt\\6.txt"); //打开文件(文件地址用双斜线替换)
try {
FileOutputStream file = new FileOutputStream(fp); //输出流
file.write("helloworld!"); //输出想打印的内容
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} catch (Exception e) {
e.printStackTrace();
}
希望能帮到大家!