用Java读取.txt文件?

用Java读取.txt文件?

问题描述:

我正在创建以下程序,该程序读取text.file并根据给出的参数打印出某些内容。如果用户输入“运行配置文件text.txt”,我希望它逐行输出文件。如果用户输入“运行配置文件text.txt 5”,则应打印出前5行。我有以下程序写:用Java读取.txt文件?

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初学者,但相信不应该有任何错误。然而,当我输入“运行配置文件的text.txt 5”,我得到下面的输出:

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

为什么我不能得到“等等等等”的行打印出来?我阅读.txt文件的方式有错误吗?我如何访问此文本文件中的行?任何建议都会有帮助。

+3

这是调试的时间。一个建议,用'Main'类分开'Profile'类,将'Profile a,b'移到局部变量 –

+0

我不明白这两个'Profile'构造函数的用途,因为它们似乎没有被使用。 – Bazinga

+0

我敢肯定,您的扫描仪读取字符串文件,而不是实际的文件。也从构造函数 – Karthikeyan

您正在扫描文件的名称,而不是文件的内容。那就是:

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

创建ScannerString本身读取。试试类似:

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

这应该读取文件的内容。