将文件作为命令行参数传递并读取其行
这是我在互联网上找到的用于读取文件行的代码,我也使用eclipse,并在其参数字段中将文件名称作为SanShin.txt传递。 但它会打印:
Error: textfile.txt (The system cannot find the file specified)
码:
public class Zip { public static void main(String[] args){ try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("textfile.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
请帮我解释为什么会出现这个错误。 谢谢
... // command line parameter if(argv.length != 1) { System.err.println("Invalid command line, exactly one argument required"); System.exit(1); } try { FileInputStream fstream = new FileInputStream(argv[0]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Get the object of DataInputStream ... > java -cp ... Zip \path\to\test.file
当您只指定"textfile.txt"
,操作系统将在该程序的工作目录中查找该文件。
您可以使用类似new FileInputStream("C:\\full\\path\\to\\file.txt")
指定文件的绝对路径
此外,如果您想知道程序运行的目录,请尝试: System.out.println(new File(".").getAbsolutePath())
您的new FileInputStream("textfile.txt")
是正确的。 如果它抛出该exception,则在运行程序时当前目录中没有textfile.txt
。 你确定文件的名称实际上不是testfile.txt
(注意s
,而不是x
,在第三个位置)。
偏离主题 :但是您之前删除的问题询问了如何逐行读取文件(我认为您不需要删除它,FWIW)。 假设你还是一个初学者并且掌握了一些东西,一个指针:你可能不想使用FileInputStream
,这是用于二进制文件,而是使用java.io
的Reader
接口/类集。 (包括FileReader
)。 此外,只要有可能,使用接口声明变量,即使将它们初始化为特定的类,例如, Reader r = new FileReader("textfile.txt")
(而不是FileReader r = ...
)。
- JAX-RS非常适合实现REST。 你用什么来用Java调用REST服务?
- Methods.class中的代码重用与策略模式和dependency injection
- 如何按需加载javafx.scene.image.Image?
- jar子似乎不再签名了。 JARSigningException:找到无符号条目
- java类/exception表的最大大小
- 在java中成功初始化Corba通知服务,但无法在linux中获取任何事件,但它在Windows中完成
- 编写Spring Resource Boundle时是否有单一规则来处理单引号?
- 扩展JFrame总是一个坏主意吗?
- JPA和Hibernate中@MapKey,@ MapKeyColumn和@MapKeyJoinColumn的区别