Java从文件读入以及读出至文件

来源:互联网 发布:网络剧备案号 编辑:程序博客网 时间:2024/06/05 01:18

RT(目前为了比赛使用,并未深究...)

读入1:

try {//创建读取字符数据的流对象。 //读取路径不正确时会抛 IOException //用一个读取流对象关联一个已存在文件。   //用Reader中的read方法读取字符。 FileReader reader = new FileReader("in.txt");int ch = 0;while((ch = reader.read()) != -1) {  //System.out.print((char)ch); if(ch == ' ') continue;System.out.print(ch-'0' + " ");}  reader.close();} catch (IOException e) {e.printStackTrace();}


读出1:

try {////打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件FileWriter writer = new FileWriter("out.txt", true);for(int i = 1; i <= 10; ++i) {writer.write(i + " ");}writer.close();} catch (IOException e) {e.printStackTrace();}


读入2:

File file = new File("in.txt");Reader reader = null;try {System.out.println("以字符为单位读取文件内容,一次读一个字节:");// 一次读一个字符reader = new InputStreamReader(new FileInputStream(file));int tempchar;while ((tempchar = reader.read()) != -1) {// 对于windows下,\r\n这两个字符在一起时,表示一个换行。// 但如果这两个字符分开显示时,会换两次行。// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。if (((char) tempchar) != '\r') {// System.out.print((char) tempchar);if(tempchar == ' ') continue;System.out.print(tempchar-'0');}}reader.close();}catch (Exception e) {e.printStackTrace();}


读出2:

        try {            // 打开一个随机访问文件流,按读写方式            RandomAccessFile randomFile = new RandomAccessFile("out.txt", "rw");            // 文件长度,字节数            long fileLength = randomFile.length();            //将写文件指针移到文件尾。            randomFile.seek(fileLength);            //randomFile.writeBytes("77654321");            for(int i = 0; i < 10; ++i)            randomFile.writeBytes(i+" ");            randomFile.close();        } catch (IOException e) {            e.printStackTrace();        }


继续加油~

原创粉丝点击