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 }
  • 相关阅读:
    samtools获取uniq reads
    NSDate的比较
    UIViewAlertForUnsatisfiableConstraints布局问题
    如何将网页保存为pdf
    使用Carthage管理iOS依赖库
    输出格式
    解决问题思路
    重:将好用的控件,上次github,
    解决CocoaPods慢的小技巧
    swift开发笔记28 CoreML
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/5253878.html
Copyright © 2011-2022 走看看