编写一个java程序将26个英文字母写入文件D:\out.txt中。(

原问题:编写一个java程序将26个英文字母写入文件D:\out.txt中。(
分类:编程开发 > 最后更新时间:【2016-12-17 02:53:53】

最佳答案

import java.io.File;

import java.io.RandomAccessFile;

public class AddCharacter {

private static RandomAccessFile accessFile;// 定义RandomAccessFile对象对文件进行操作

private static String dir = "D:\\out.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 ---------------");

}

}


  • 追问:
    多谢
    最佳答案由网友  狂仙_2012  提供
  • 公告: 为响应国家净网行动,部分内容已经删除,感谢网友理解。
    16

    分享到:

    其他回答

    暂无其它回答!

      推荐