简体   繁体   中英

how to read text file in java program

this is my java code. 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

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. 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:

      javac ShowFile.java

Pass The Command line argument:

      java ShowFile file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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