java===java基础学习(5)---文件读取,写入操作

文件的写入读取有很多方法,今天学到的是ScannerPrintWriter

文件读取

Scanner in = new Scanner(Paths.get("file.txt"))

文件写入

PrintWriter out = new PrintWriter("file.txt")

  • 文件读取的我目前只发现他是一行一行的读取不能整篇幅的读取,所以写了一个while循环,一行行的打印。
  • 文件写入,写入的文件不能实现追加模式的写入。会把之前内容覆盖掉。
  • 文件操作完,记得进行close()。
//Scanner文本文件读取与处理
package testbotoo;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Scanner;


public class file {
    public static void main(String[] arg) throws IOException{
        //文件读取
        Scanner in = new Scanner(Paths.get("C:\\Users\\...\\Desktop\\myfile.txt")); //读取文件操作
        while(in.hasNextLine()){
            String str = in.nextLine();
            if(str.equals("9999")){
                break;
            };
            System.out.println(str);
        }
        in.close();
        //文件写入
        PrintWriter out = new PrintWriter("C:\\Users\\...\\Desktop\\myfile.txt");
        out.println("ssss");
        out.println("5466555");
        out.close();
    }
    

}

 

 

由于不能写追加写入,又找到了一种新的解决办法:

    import java.util.*;
    import java.io.*;
    public class T {
        public static void main(String[] args) {
            String fileName = "data.txt";
            FileWriter fw = null;
            PrintWriter toFile = null;
            try {
                fw = new FileWriter(fileName, true); //  throw IOException
                toFile = new PrintWriter(fw); // throw FileNotFoundException
            } catch (FileNotFoundException e) {
                System.out.println("PrintWriter error opening the file " + fileName);
                System.exit(0);
            } catch (IOException e) {
                System.out.println("FileWriter error opening the file " + fileName);
                System.exit(0); 
            } 
            System.out.println("Enter four lines of text:");
            Scanner keyboard = new Scanner(System.in);
            for (int count = 1; count <= 4; count++) {
                String line = keyboard.nextLine();
                toFile.println(count + " " + line);
            } 
            System.out.println("Four lines were written to " + fileName);
            toFile.close();
        }
    }

 

转载于:https://www.cnblogs.com/botoo/p/8482472.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值