java读写作为命令行参数传递的文件
我试图弄清楚如何将两个文件(input.txt和output.txt)作为参数传递给我的main方法,读取输入文件,将其传递给递归方法,然后将经过修改的字符串写入输出文件。我以前从未使用过命令行参数,所以我不知道如何让它工作。以下是迄今为止的代码:
public static void main(String[] args)
{
ArrayList<String> fileInput = new ArrayList<String>();//ArrayList to hold data from input file
File file = new File(args[0]);
try
{
Scanner scan = new Scanner(new File(args[0]));
FileInputStream readFile = new FileInputStream("input.txt"); // readFile passed from args[0]; args[0] is the argument passed as a string that is held at the 0 index of the args array
fileInput.add(file); //red error line under Add
}
catch(IOException e)
{
e.printStackTrace();
System.exit(0);
}
ArrayList<String> strArray = new ArrayList<String>();
String s;
for(int i = 0; i < file.length() ; i++) //int i = 0; length of stored string data object; i++)
{
//recursiveMarkUp is a string type
strArray.add(file.recursiveMarkUp());//call the markup method and save to an array so we can print to the output file later
//line to print output to output.txt
}
}
# 1 楼答案
传入参数时,它们存储在
args[]
数组中,并像main
中的任何普通数组一样被访问您指出红色错误行的注释之所以出现,是因为您试图将
File
对象添加到ArrayList<String>
对象,但该对象不兼容。但是,无论如何,没有必要执行此步骤您可以使用上面的文件构造输出流:
如果您使用的是Java 8+,那么使用
Files.lines()
可以将文件的每一行作为String
流进行处理要在没有流的情况下实现这一点:
为了简洁起见,我排除了try/catch块。我还假设您确实希望一次处理一行输入文件;如果不是这样,根据需要进行调整。在读/写数据时,您还应该考虑显式定义文件编码(UTF-8等),虽然在这里我也把它保留为简洁。p>