Java-我想从命令行读取一个文件名,然后使用BufferedReader读取每一行 [英] Java - I want to read a file name from command line then use a bufferedreader to read each line

查看:45
本文介绍了Java-我想从命令行读取一个文件名,然后使用BufferedReader读取每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在

上看到日食红色下划线错误
 br = new BufferedReader(new FileReader(inFile));

"inFile"上的行。这是我想要读取的对象,我相信它包含了我在命令行中给它的命令行文件名/路径。我是否处理错了?

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

     public static void main(String[] args) {
      if (0 < args.length) {
          File inFile = new File(args[0]);
      }

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader(inFile));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } 

        catch (IOException e) {
            e.printStackTrace();
        } 

        finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

推荐答案

更改:

if (0 < args.length) {
    File inFile = new File(args[0]);
}

至此:

File inFile = null;
if (0 < args.length) {
   inFile = new File(args[0]);
} else {
   System.err.println("Invalid arguments count:" + args.length);
   System.exit();
}

因为file变量无法在if/else语句外部访问。

我已在else中(对于未提供args的情况)添加了一条友好消息,说明参数计数无效并退出程序。

这篇关于Java-我想从命令行读取一个文件名,然后使用BufferedReader读取每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆