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 }
  • 相关阅读:
    Git_创建版本库
    Git_安装Git
    Git_集中式vs分布式
    Git_git的诞生
    echartShow
    微信小程序红包开发 小程序发红包 开发过程中遇到的坑 微信小程序红包接口的
    vue2.0 $router和$route的区别
    vue移动端开发全家桶
    干货分享:vue2.0做移动端开发用到的相关插件和经验总结
    优秀的基于VUE移动端UI框架合集
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/5253878.html
Copyright © 2011-2022 走看看