java使用追加的形式将26个小写字母写入到一个txt文件中
2个回答
展开全部
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 ---------------");
}
}
推荐于2018-04-27
展开全部
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.
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.
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询