zoukankan      html  css  js  c++  java
  • java 从指定行读文件,执行系统命令

     1 import java.util.*;
     2 import java.io.*;
     3 
     4 public class Example {
     5     public static void main(String[] args){
     6         readFile("proxy.txt",0);
     7         readFile("proxy.txt",1);
     8         readFile("proxy.txt",4);
     9         execSystemCmd("notepad"); // windows cmd
    10         execSystemCmd("ls /home/whucs");
    11         execSystemCmd("tail -n /home/whucs/vote.py");
    12         execSystemCmd("wc -l php-fpm.log"); // count lines of a file. 500MB ~ 2s
    13     }
    14     
    15     public static void readFile(String path, int beginLine) {
    16         FileInputStream inputStream = null;
    17         Scanner sc = null;
    18         try {
    19             inputStream = new FileInputStream(path);
    20             sc = new Scanner(inputStream, "UTF-8");
    21             int begin = 0;
    22             if (beginLine == 0) beginLine = 1;
    23             while (sc.hasNextLine()) {
    24                 begin ++;
    25                 if (begin >= beginLine) {
    26                     String line = sc.nextLine();
    27                     // TODO...
    28                     System.out.println(line);
    29                 } else {
    30                     sc.nextLine();
    31                 }
    32             }
    33             if (begin < beginLine) {
    34                 System.out.println("error! beginLine > file's total lines.");
    35             }
    36             inputStream.close();
    37             sc.close();
    38         } catch (IOException e) {
    39             System.out.println("FileReader IOException!");
    40             e.printStackTrace();
    41         }
    42     }
    43     
    44     public static void execSystemCmd(String cmd) {
    45         String outPut = null;
    46         System.out.println("cmd=" + cmd);
    47         try 
    48         {
    49             Process p = Runtime.getRuntime().exec(cmd);
    50             InputStream is = p.getInputStream();
    51             BufferedReader br = new BufferedReader(new InputStreamReader(is));
    52             StringBuilder buf = new StringBuilder();
    53             String line = null;
    54             while ((line = br.readLine()) != null)    buf.append(line + "
    ");            
    55             outPut = buf.toString();
    56             System.out.printf("outPut = %s",outPut);
    57         } 
    58         catch (IOException e) 
    59         {
    60             e.printStackTrace();
    61         }
    62     }
    63     
    64 }
  • 相关阅读:
    快递员—你惹不起的“组织”
    BF的真正意义
    读书:《四点起床-最养生和高效的时间管理》
    你究竟有多想成功?汗水铸造巨星(中英结合版含视频)
    美国女生给我的六个惊诧(转)
    据说是世界上最健康的作息
    少走弯路的十条忠告
    编程—休息片刻的好处
    学电脑必懂的53个英文单词和缩写
    四件在我步入职业软件开发生涯那天起就该知道的事情
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/5253878.html
Copyright © 2011-2022 走看看