有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    传入参数时,它们存储在args[]数组中,并像main中的任何普通数组一样被访问

    File input = new File(args[0]);
    File output = new File(args[1]); // make sure you check array bounds
    

    您指出红色错误行的注释之所以出现,是因为您试图将File对象添加到ArrayList<String>对象,但该对象不兼容。但是,无论如何,没有必要执行此步骤

    您可以使用上面的文件构造输出流:

    output.createNewFile(); // create the file so that it exists before writing output
    FileOutputStream outStream = new FileOutputStream(output);
    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
    

    如果您使用的是Java 8+,那么使用Files.lines()可以将文件的每一行作为String流进行处理

    Files.lines(input.toPath())
        .map(line -> recursiveMarkup(line))
        .forEach(markedUp -> outWriter.write(markedUp));
    

    要在没有流的情况下实现这一点:

    BufferedReader reader = new BufferedReader(new FileReader(input));
    String line = "";
    while(line != null) {
        line = recursiveMarkup(reader.readLine());
        outWriter.write(line);
    }
    

    为了简洁起见,我排除了try/catch块。我还假设您确实希望一次处理一行输入文件;如果不是这样,根据需要进行调整。在读/写数据时,您还应该考虑显式定义文件编码(UTF-8等),虽然在这里我也把它保留为简洁。p>