java文件读取和写入

基本方法

读取文件内容是非常重要的,实际的业务应用场景几乎都是读取文件的,需要用到FIle、FileInputStream、FileReader、BufferedReader等实现文件读取。
这里总结基本的读取方式,并给出应用实例。

使用Scanner读取数据

java.util.Scanner类,Scanner读取内容,空格作为分隔标记。
Scanner input = new Scanner(new File(filename));是它的具体实现方式。

其中连续读取字符内容可以使用input.next()或input.hasnext(),具体next()的返回值是文件里面的内容,hasnext()的返回值是boolean类型。

public class TestScanner {
    public static void main(String[] args) throws IOException {
        File file = new File("src/File/ScannerFile");

        Scanner sc = new Scanner(file);
        while (sc.hasNext()){
            String firstName = sc.next();
            String secondName = sc.next();
            String lastName = sc.next();
            System.out.println(firstName + " " + secondName + " " + lastName +" ");
        }
        sc.close();
    }
}

使用PrintWriter写入数据

java.io.PrintWriter类,创建文件并写入数据(不能读取)。

使用PrintWriter output = new PrintWriter(filName);创建新文件,利用 println, print, printf写入数据。

public class test {
    public static void main(String[] args) {
        //Init file
        File file = new File("src/File/printWriterFile.txt");

        //if exist
        if (file.exists()){
            System.out.println("File srcfile.txt aready exists");
            System.exit(1); //exist and exit
        }

        //if not exist
        try {
             PrintWriter output = new PrintWriter(file);
             //write data
             output.print("hello world");
             output.println(80);
             output.print("I am codepig");
             output.print(50);
             //close stream
             output.close();
             //如果使用try-with-resources结构,系统会自己关闭文件,不用手动close()
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

//  I am codepig 
//  You are pig 
//  i m l 

简单应用

输出当行,并计算text文件里面的空格个数

  • file.txt
Record 1:How many stages are there in the traditional software development model?
Record 2: After entering the room, walk to the person sitting nearest to you and greet him/her with a “high five”.
Record 3: What are encapsulated into an object?
Record 4: What diagram is the following diagram? Simply describe the meaning of it.
  • BlankCount.java
public class BlankCount {
    public static void readAndCount(String path) throws IOException {
        //创建数据流对象
        File file;  //文件对象
        InputStream inputStream;
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader;

        try {
            file = new File(path);
            inputStream = new FileInputStream(file);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //字符串处理
            while (bufferedReader.ready()){
                String line = bufferedReader.readLine();
                stringBuffer.append(line);
                System.out.println(line);
                System.out.println("上一行的空格个数为:"+count(stringBuffer.toString()," "));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    //count blank num
    public static int count(String sourceString ,String findString){
        int index = 0;
        int countAns = 0;
        while ((index = sourceString.indexOf(findString,index)) != -1){
            index = index+findString.length();
            countAns++;
        }
        return countAns;
    }

    public static void main(String[] args) throws IOException {
        readAndCount("src/File/file.txt");
    }
}

输出结果:
这里插入图片描述](https://img-blog.csdnimg.cn/20200530215556319.png)

猜你喜欢

转载自blog.csdn.net/fazijiaidama/article/details/106447823
今日推荐