此程序实现了创建一个文件夹及其两个子文件,一个为data.txt,一个为filenew.txt,文件夹名字为create,程序包名为readW
import java.io.*;
public class createFile {
public static void main(String[] arg) throws IOException{
String s;
File file = new File("create");
if(!file.exists()){
file.mkdir();
}
if(file.isDirectory()){
File nfile = new File(file,"filenew.txt");
File ndata = new File(file,"data.txt");
if(!nfile.exists()){
try {
nfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("文件的绝对路径为:"+nfile.getAbsoluteFile());
if(!ndata.exists()){
ndata.createNewFile();
}
System.out.println("文件的绝对路径为:"+ndata.getAbsoluteFile());
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(ndata)));
int a = 0;
int b = 1;
int temp;
while(b < 1000){
temp = b;
b = a+b;
a = temp;
pw.print(a+"\t");
}
pw.close();
}
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Program Files\\Java\\新建文件夹\\Diary\\ReadW\\create\\filenew.txt"));
System.out.println("文件的内容为:");
try {
while((s = br.readLine())!=null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
程序读取文本内容为:
程序向文本里写入斐波那契数列:
这里要注意几个问题:
1.一开始找一个bug找了很久,这时候文件夹和文件都已经新建了,当时我写的输出文件绝对路径的代码写在了判断文件是否存在的if语句内,导致只有第一次能输出路径,所以保险的做法是把输出路径语句写在外面。
2.出现错误filenotfound,说明要读取的文件没有在工程所在的目录下,因此保险的做法是将文件的绝对路径作为参数。
其实仔细分析程序可以发现,
新建一个文件夹、文件分成固定的两步套路:
File file = new File(“create”);//1.先new出来;
file.mkdir();//2.创建
File nfile = new File(file,”filenew.txt”);
nfile.createNewFile();
只是说涉及到异常的处理,要么就要try catch,要么就要throws抛出异常;
其次,标准输入输出和字节流字符流的转换,就要用到匿名字符流等类。