• Java初学者笔记四:按行读写文件和输入处理


    一、我们来看python的很简单:

    1、读文件:

    1 with open("/path/file","r") as fr:
    2     for line in fr.readlines():
    3         do_somethings(line)

    2、写文件:

    1 with open("/path/file","w/a") as fr:
    2     fr.write("ssssssss")

    二、上文知识一个引子,不是重点,还是来学习java的文件读写操作吧:

    最常用的还是按行读写,当然后面也会带一点其他读写方法:

    1、按行读取:

    1 File file = new File("绝对路径");
    2 BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    3 String str = null;
    4 while((str = bufferedReader.readLine()) != null)  
    5 {  
    6     System.out.println(str);  
    7 }
    8 bufferedReader.close();

    2、按行写入:

    1 FileWriter filew = new FileWriter("绝对路径",true);
    2 //true表示追加,否则是覆盖写,覆盖写不需要true
    3 filew.write("
    test
    ");
    4 filew.close();
    1 List<String> b = Files.readAllLines(Paths.get("/Users/a003797/Desktop/a1.txt"));
    2 for(String item:b) {
    3     System.out.println(item)    ;    
    4 }

    3、其他读取方式:

    1 //读取全部字节:
    2 byte[] a = Files.readAllBytes(Paths.get("/Users/a003797/Desktop/a1.txt"));

    三、输入处理

     1 import java.io.*;
     2 
     3 public class test{
     4     public static void main(String args[]) throws IOException {
     5         BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));    
     6         while(true){
     7             String string = br.readLine();
     8             System.out.println(string);
     9         }
    10     }
    11 }
  • 相关阅读:
    教你OpenCV3.2.0+VS2017开发环境配置
    使用conda 与pip命令管理Python库
    【Python+OpenCV】Windows+Python3.6.0(Anaconda3)+OpenCV3.2.0安装配置
    GitHub Toturial
    C 语言多线程与锁机制
    翻译 | Placing Search in Context The Concept Revisited
    翻译 | Improving Distributional Similarity with Lessons Learned from Word Embeddings
    Derivative of Softmax Loss Function
    从头推导与实现 BP 网络
    施密特正交化 GramSchmidt
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/8550374.html
Copyright © 2020-2023  润新知