2013-11-22 36 views
0

如何讓此程序在命令行的「lab13.txt」中讀取?我一直試圖弄清楚這個問題一個多小時,沒有任何工作。如何使程序使用您在命令行中指定名稱的文件

提示是「編寫一個程序,確定並顯示在命令行中指定名稱的文件中的行數。使用lab13.txt測試您的程序。」

import java.util.Scanner; 
import java.io.*; 
class homework 
{ 
    public static void main(String[] args) throws IOException 
    { 
     Scanner inFile= new Scanner(new File("lab13.txt")); 
     int count=0; 
     String s; 
     while (inFile.hasNextLine()) 
     { 
      s = inFile.nextLine(); 
      count++; 
     } 
     System.out.println(count + " Lines in lab13.txt"); 
     inFile.close(); 
    } 
} 

回答

0

如果你希望用戶使用此

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Please enter filename : "); 
    String filename = null; 
    try { 
     filename = reader.readLine(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

然後,您可以將文件名插入您的掃描對象可以輸入命令行或控制檯在eclipse試試文件名

0
Try this 

在你的代碼需要new File(args[0])

更換new File("lab13.txt")對於命令行

public static void main(String[] args) { 

File inFile =null; 
    if (0 < args.length) { 
     File inFile = new File(args[0]); 
    } 

    BufferedReader br = null; 

    try { 

     String sCurrentLine; 

     br = new BufferedReader(new FileReader(inFile)); 

     while ((sCurrentLine = br.readLine()) != null) { 
      System.out.println(sCurrentLine); 
     } 

    } 

    catch (IOException e) { 
     e.printStackTrace(); 
    } 

    finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

的特定地點

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

public class BufferedReaderExample { 

    public static void main(String[] args) { 

     BufferedReader br = null; 

     try { 

      String sCurrentLine; 

      br = new BufferedReader(new FileReader("C:\\lab13.txt")); 

      while ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(sCurrentLine); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 
} 
相關問題