简体   繁体   English

如何从在java中的命令行参数中给出的文件中读取?

[英]how to read from file that was giving in a command line argument in java?

I want to read from file , where the program gets the file name ( the file is also a java file) from command line argument , and then prints only the comments from the file i want to read from the file using java.nio.file.Files and java.nio.file.Path maybe.我想从文件中读取,其中程序从命令行参数获取文件名(该文件也是一个 java 文件),然后只打印我想使用java.nio.file.Files从文件中读取的文件中的注释java.nio.file.Filesjava.nio.file.Path也许。 i am supposed to read the file name using the main function i don't know how to do that , any help plz ?我应该使用主函数读取文件名我不知道该怎么做,有什么帮助吗? this is actually my first ever code i write in java so i am having a lot of difficulties here is what i have so far :这实际上是我用 Java 编写的第一个代码,所以我遇到了很多困难,这是我迄今为止所遇到的:

package firtJavaCode;

import java.io.*; 
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
import java.lang.String ;

public class ReadFromFile {

    public static void main(String[] args) {
        try {
            //String filePath = "";   // here is my problem i don't know how to read from a giving file
            String line;
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            int lineNumber = 0;
            while ((line = br.readLine()) != null) {
                lineNumber++;
                if  (line.contains("//")) {
                     StringTokenizer st1 =  new StringTokenizer(line, "//");            
                     System.out.println(st1.nextToken()); 
                }
                
                // i still didn't complete the code , just want to figure how to read from file first
            }
        }catch (Exception e) {
            System.out.println(e);
        }
    }
}

You have the arguments which are written in the console in the String[] args array.您有在 String[] args 数组中写入控制台的参数。 To get the filename we assume that you execute the program like this: java example /home/file.txt .为了获取文件名,我们假设您像这样执行程序: java example /home/file.txt

args[0] == "/home/file.txt"

So the filepath is saved in args[0] as a string already so you won't need the extra String filepath in the code.因此文件路径已作为字符串保存在args[0] ,因此您不需要代码中的额外String filepath

BufferedReader br = new BufferedReader(new FileReader(args[0]));

So basically the arguments that you put in after the program name are saved all in the String args[] array.所以基本上你在程序名称之后放入的参数都保存在String args[]数组中。

I also would implement a way to check if only the filepath is entered and not some other crap like this:我还将实现一种方法来检查是否只输入了文件路径,而不是像这样的其他一些废话:

if (args.length() > 0)
{
    System.out.println("Error! Too many arguments entered!");
}

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

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