zoukankan      html  css  js  c++  java
  • [Java文件操作] 为文本文件添加行号

    【思路】将文件中的内容按行读取存入一个字符串中,在输出时再为每一行加上行号。

     1 import java.io.*;
     2 public class Text {
     3     private String strFinal = "";
     4     public void open(String fileName) {
     5         try {
     6             BufferedReader in = new BufferedReader(new FileReader(fileName));
     7             String s = null;
     8             while ((s = in.readLine()) != null) {
     9                 strFinal = strFinal + s + "
    ";
    10             }
    11             in.close();
    12         } catch (IOException e) {
    13             System.out.println(e);
    14         }
    15     }
    16     public void save(String fileName){
    17         try{
    18             BufferedReader in = new BufferedReader(new StringReader(strFinal));
    19             PrintWriter out = new PrintWriter(new FileWriter(fileName));
    20             int lineCount = 1;
    21             String s = null;
    22             while((s = in.readLine())!=null){
    23                 out.println(lineCount+++": "+s);
    24             }
    25             in.close();
    26             out.close();
    27         }catch(IOException e){
    28             System.out.print(e);
    29         }
    30     }
    31     public static void main(String args[])throws IOException{
    32         Text obj = new Text();
    33         obj.open("D:/Java_workspace/Text/src/Text.java");
    34         obj.save("E:\Example\A.txt");
    35     }
    36 }
  • 相关阅读:
    函数
    vue中v-for循环如何将变量带入class的属性名中
    代码规范 前端导航
    2019.8.5 mysql 删除 更新
    2019.8.1
    2019.7.31 Xshell简单学习
    日常使用知识点
    FormData实现文件多次添加累加上传和选择删除
    上传图片
    验证码
  • 原文地址:https://www.cnblogs.com/lca1826/p/6498687.html
Copyright © 2011-2022 走看看