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 }
  • 相关阅读:
    【并查集学习笔记】------迟来的总结
    【Ant Trip】题解
    【数星星 Stars】题解
    【From Hero to Zero】题解
    营救 【题解】
    js获取浏览器视窗尺寸
    js基础拖拽二
    js基础拖拽一
    js检测浏览器flash支持
    js操作cookie
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/5253878.html
Copyright © 2011-2022 走看看