欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件输入输出(java)

程序员文章站 2022-03-01 18:06:20
...

文件输入输出(RandomAccessFile类)
1.使用RandomAccessFile流将一个文本文件倒置读出。

import java.io.*;
import java.util.Scanner;

public class Test {
    public static void main(String args[]){
        RandomAccessFile in = null;
        String str = "hello jsjfosfnso12345fijsmsjijdifjsfm hello";
        try {
            File file = new File("D:\\java","text.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            in = new RandomAccessFile(file,"rw");
            for(int i = 0;i < str.length();i++) {
                in.write(str.charAt(i));           //把字符串写入文件中
            }
            in.writeUTF(str);
            long len = str.length();               //获得字符串长度
            for(long i = len-1;i >= 0;i--) {
                in.seek(i);                        //设置文件指针,定位文件的读写位置
                char c = (char)in.read();
                System.out.print(c);
            }

            /*long length = in.length();
            long position = 0;
            in.seek(position);
            while(position < length){
                String ss = in.readLine();
                byte[] b = ss.getBytes("ISO-8859-1");       //若文件中有汉字,则需要重新编码
                ss = new String(b);
                position = in.getFilePointer();
                System.out.println(ss);
            }
            */
            in.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

2.使用Java的输入流、输出流将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。


import java.io.*;
import java.util.Scanner;

public class Test {
    public static void main(String args[]) throws IOException{
        File file = new File("D:\\java\\text.txt");
        File file1 = new File("D:\\java\\text1.txt");
        if(!file1.exists()) {
            file1.createNewFile();
        }
        if(!file.exists()) {
            file.createNewFile();
        }
        try {
            FileReader inOne = new FileReader(file);
            BufferedReader inTwo = new BufferedReader(inOne);     //读入文件
            BufferedWriter outTwo = new BufferedWriter(new FileWriter(file1));    //写入新的文件
            String s = " ";
            int i = 0;
            while((s = inTwo.readLine()) != null) {
                i++;
                outTwo.write(i+" ");
                outTwo.write(s);
                System.out.println(s);
                outTwo.newLine();
            }
            outTwo.flush();
            outTwo.close();
            inOne.close();
            inTwo.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
相关标签: Java