java使用追加的形式将26个小写字母写入到一个txt文件中
发布网友
发布时间:2024-10-06 07:04
我来回答
共2个回答
热心网友
时间:2024-10-06 10:52
import java.io.File;
import java.io.RandomAccessFile;
/**
*
* @author sie1501
*
*/
public class AddCharacter {
private static RandomAccessFile accessFile;// 定义RandomAccessFile对象对文件进行操作
private static String dir = "D:\\char.txt";// 文件路径
/**
* 往文件追加新的字符
*
* @param newChar
* 字符
* @return 追加成功返回true,否则返回false
*/
public static boolean addChar(char newChar) {
try {
File file = new File(dir);
accessFile = new RandomAccessFile(file, "rw");
long length = file.length();// 获取文件长度
accessFile.seek(length);// 末尾处添加内容
accessFile.writeChars(String.valueOf(newChar));// 写入操作
accessFile.close();
return true;
} catch (Exception e) {// 异常捕获
// TODO: handle exception
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
for (char charIndex = 'a'; charIndex <= 'z'; charIndex++) {
if (!addChar(charIndex)) {// 错误提示
System.out.println("Add character: " + charIndex + " was failure");
}
}
System.out.println("-------------- End ---------------");
}
}
热心网友
时间:2024-10-06 10:53
FileOutputStream 的构造中,有参数
FileOutputStream(String name,
boolean append)
Creates an output file stream to write to the file with the specified
name.
FileOutputStream(File file,
boolean append)
Creates a file output stream to write to the file represented by
the specified File object.