java,编写一个在文件尾追加新数据的程序Test1.java

编写一个在文件尾追加新数据的程序Test1.java。如果InputFile1.dat文件不存在,则以该名字创建文件,并打印提示信息“文件不存在,创建文件“。如果该文件存在,在文件尾追加字符a~z,字符之间以制表符来分隔,结束时打印提示信息“数据传送完成“。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Test1 {

//测试方法
public static void main(String[] args) {
Test1 test1 = new Test1();

try {
test1.appendFile();
test1.appendFile();
} catch (IOException e) {
e.printStackTrace();
}
}

//文件名称,默认存到类路径下
public static final String FILENAME="InputFile1.dat";

public void appendFile() throws IOException {
String outPath = getOutputFileName();
//第二个参数以追加的方式写入文件
Writer writer = new FileWriter(outPath, true);
try{
         int begin = (int)'A';
         int end = (int)'Z';
         for(int i= begin;i <= end;i++){
         writer.append((char)i);
         if((char)i != 'Z') {
         writer.append('\t');
         }else{
         writer.append('\n');
         }
         }
}finally{
writer.close();
}
}

private String getOutputFileName() throws IOException {
String path = this.getClass().getResource("").getPath()+"/"+FILENAME;
File file = new File(path);
if(!file.exists()) {
System.out.println("文件不存在,创建文件");
file.createNewFile();
}
return path;
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-06-27

参考代码和注释如下

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Test1 {
public static void main(String[] args) {
String fp = "InputFile1.dat";//文件名

File f = new File(fp);//文件对象
if(!f.exists()){//如果文件不存在
try {
f.createNewFile();//创建文件
System.out.println("文件不存在。创建文件");
} catch (IOException e) {
e.printStackTrace();
}
}

try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));//参数true表示在文件末尾添加数据
StringBuffer info = new StringBuffer();//用于拼接字符串
for (char i = 'a'; i < 'z'; i++) { //注意变量时char 类型
info.append(i+"\t");//用制表符分开
}
info.append('z');//最后一个字符z 就不用制表符了
bw.write(info.toString());
bw.close();
System.out.println("数据传送完成");
} catch (IOException e) {
e.printStackTrace();
}

}
}

测试

床前明月光,疑是地上霜。
举头望明月,低头思故乡a b c d e f g h i j k l m n o p q r s t u v w x y z

本回答被网友采纳
相似回答