简体   繁体   English

如何在Java程序中读取文本文件

[英]how to read text file in java program

this is my java code. 这是我的Java代码。 Please tell where i have to change the code so that i could be able to read the data from my text file ie test.txt 请告诉我我必须在哪里更改代码,以便我能够从我的文本文件即test.txt中读取数据

import java.io.*;

class ShowFile {
    public static void main(String args[]) throws IOException {
        // this is my file where my data is: test.TXT;
        int i;
        FileInputStream fin;

        try {
            fin = new FileInputStream(args[0]);
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            return;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Usage: ShowFile File "+ e);
            return;
        }

        // read characters until EOF is encountered
        do {
            i = fin.read();
            if (i != -1)
                System.out.print((char) i);
        } while(i != -1);

        fin.close();
    }
}

您需要更改此行才能读取文件

       fin = new FileInputStream(yourfile);

You're opening the input stream here: 您要在此处打开输入流:

fin = new FileInputStream(args[0]);

it's using the first argument to main (from the command line) args[0] you can change that to your specific file. 它使用main(从命令行) args[0]的第一个参数,您可以将其更改为您的特定文件。 Or just pass your file in. 或者只是传递您的文件。

做这个:

fin = new FileInputStream(path to your file);

Try This : 尝试这个 :

      String s=args[0];
      fin = new FileInputStream(s);

Compile java File: 编译java文件:

      javac ShowFile.java

Pass The Command line argument: 传递命令行参数:

      java ShowFile file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM