文件输入输出(java)

文件输入输出(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)