zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    笔记:Maven 聚合和继承
    笔记:Maven 仓库和插件配置本机私服
    笔记:Maven 插件配置
    笔记:Maven 仓库及配置详解
    笔记:Maven 插件及配置详解
    笔记:Maven 依赖及配置详解
    笔记:Maven 项目基本配置
    【问题解决方案】Mathtype中丢失Mplugin.dll的问题
    【学习总结】Python-3-字符串函数-strip()方法
    【学习总结】Python-3-字符串函数split()的妙用
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/8550374.html
Copyright © 2011-2022 走看看