簡體   English   中英

使用Java讀取.txt文件?

[英]Reading .txt file with Java?

我正在創建以下程序,該程序讀取text.file並根據給定的參數打印出某些內容。 如果用戶輸入“運行配置文件text.txt”,我希望它逐行打印出文件。 如果用戶輸入“ run Profile text.txt 5”,則應該打印出前5行。 我編寫了以下程序:

import java.util.*; 
import java.io.*; 

public class Profile{

  public static String file;
  public static int len;
  public static Profile a;
  public static Profile b;

  //Method to read whole file
  static void wholeFile(String file){
    Scanner in = new Scanner(file);
    int lineNumber = 1;

    while(in.hasNextLine()){
      String line = in.nextLine();
      System.out.println("/* " + lineNumber + " */ " + line);
      lineNumber++;
    }
    in.close();
  }

  //Method to read file with line length
  static void notWholeFile(String file, int len){
    Scanner in = new Scanner(file);
    int lineNumber = 1;

    while(in.hasNextLine() && lineNumber <= len){
      String line = in.nextLine();
      System.out.println("/* " + lineNumber + " */ " + line);
      lineNumber++;
    }
    in.close();
  }

Profile(String file){
    this.file = file;
}
Profile(String file, int len){
    this.file = file;
    this.len = len;
    notWholeFile(file, len);
}
  public static void main(String[] args){
    Scanner in = new Scanner (System.in);
    if (args.length == 1){
      file = args[0] + "";
      a = new Profile(file);
      wholeFile(file);
    }     
    if (args.length == 2){
      file = args[0] + "";
      len = Integer.parseInt(args[1]);
      b = new Profile(file, len);
      notWholeFile(file, len);
    }   
  }
}

出於測試目的,我在目錄中包含一個名為“ text.txt”的.txt文件,其中包含以下文本:

blah blah blah blah blah blah blah
blah blah blah blah blah blah blah

blah blah blah blah blah blah blah
blah blah blah blah blah blah blah

blah blah blah blah blah blah blah
blah blah blah blah blah blah blah

blah blah blah blah blah blah blah
blah blah blah blah blah blah blah

我是Java的初學者,但我相信不應有任何錯誤。 但是,當我輸入“ run Profile text.txt 5”時,將得到以下輸出:

> run Profile text.txt 5
/* 1 */ text.txt
/* 1 */ text.txt
> 

為什么不能打印出“ blah blah”行? 我讀取.txt文件的方式是否存在錯誤? 如何訪問此文本文件中的行? 任何建議都會有所幫助。

您正在掃描文件的名稱 ,而不是文件的內容 那是:

Scanner in = new Scanner(file);  // where file is of type string

創建一個從String本身讀取的Scanner 嘗試類似:

Scanner in = new Scanner(new File(file));

這應該讀取文件的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM