用Java处理文件

时间:2019-06-05 02:14:06

标签: java

我想在代码交互后读取多个txt文件并播放一个输出文件。 如何将文件传递给代码?是三个.txt文件

import java.io.*;
import java.util.*;

public class Main1 {
    public static void main(String[] args) throws IOException{
      int n = Integer.parseInt(args[0]), i;
      if(n <= 0) return;

      String narq[] = new String[n];
      for( i = 1 ; i <= n;i++)
        narq[i - 1]= args[i];
        Merge(n, narq, args[n + 1]);
    }
    static void Merge(int n, String [] narq, String exit1) throws
    IOException{
    BufferedReader in[] = new BufferedReader[n];
    for(int i = 0; i < n; i++)
        in[i] = new BufferedReader(new FileReader(narq[i]));
    BufferedWriter out;
    out = new BufferedWriter(new FileWriter(exit1));
  }
}

2 个答案:

答案 0 :(得分:3)

除了处理文件之外,您还需要做更多的工作来处理 args [] 字符串数组。您实际上不必这样做,而是利用您拥有此变量的事实。您在 main()方法中应该具有的所有内容是:

if (args.length == 0 || args.length < 2) {
    return;
}
Merge(args);

仅此而已,只需将 args [] 字符串数组传递给您的 merge()方法,当然需要对其进行一些修改。上面的这些代码行是做什么的?

if 语句中首先检查条件args.length == 0,如果为true,则意味着没有命令行参数传递给应用程序,因此我们退出 main( )方法,并带有 return 语句,该语句最终 关闭应用程序。

但是,如果第一个条件通过(有命令行参数),则检查|| args.length < 2条件,如果提供的参数(文件名)少于两个,则再次跳出 main()方法并退出应用程序。我们至少需要2个文件名才能进行任何类型的文件合并( 源文件名 目标文件名 < / strong>)。在您的应用程序中,始终将命令行中的最后一个参数视为 目标文件路径/名称 。命令行中列出的所有其他文件都将合并到该文件中。

最后一行当然是对 merge()方法的调用,该方法可以完成所有工作。由于调用是从 main()方法内部进行的,因此 merge()方法将需要是 static 方法,并且可能看起来像这个:

/**
 * Merges supplied text files to a supplied single destination text file.<br><br>
 * 
 * @param args (1D String Array) All elements (file paths) within the array are 
 * considered files to be merged to the destination file with the exception of 
 * the very last array element. This element must contain the destination file 
 * path itself. Two or more file paths must be provided within this array 
 * otherwise no merging takes place.<br>
 * 
 * @param overwriteDestination (Optional - Boolean) Default is true whereas the
 * merge destination file is always overwritten if it exists. If false is supplied 
 * then the destination file is not overwritten and merging files are appended to 
 * the existing data within that destination file.
 */
public static void merge(String[] args, boolean... overwriteDestination) {
    boolean overwrite = true; // Default - Overwite Destination file if it exists.
    if (overwriteDestination.length > 0) {
        overwrite = overwriteDestination[0];
    }

    try ( // PrintWriter object for last file name in args array
        PrintWriter pw = new PrintWriter(new FileWriter(args[args.length - 1], !overwrite))) {

        // BufferedReader object for files in args array (except the last file).
        BufferedReader br = null;
        for (int i = 0; i < args.length - 1; i++) {
            File f = new File(args[i]);
            if (!f.exists() || f.isDirectory()) {
                System.out.println("The specified file in Command Line named " + 
                                    args[i] + " does not appear to exist! Ignoring File!");
                continue;
            }
            br = new BufferedReader(new FileReader(f));
            String line;
            /* Loop to copy each line of the file currrently
               in args[i] to the last file provided in args 
               array (last file name in command line)   */
            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
            pw.flush();

            // close reader;
            br.close();
            System.out.println("Merged " + args[i] + " into " + args[args.length - 1] + ".");
        }
    }
    catch (FileNotFoundException ex) {
        Logger.getLogger("merge() Method Error!").log(Level.SEVERE, null, ex);
    }
    catch (IOException ex) {
        Logger.getLogger("merge() Method Error!").log(Level.SEVERE, null, ex);
    }

}

根据需要修改方法以适合您的需求。

答案 1 :(得分:2)

建议使用java.nio包。这是工作代码,根据需要进行更新: 使用-c:\ a.txt c:\ b.txt c:\ c.txt

之类的参数运行
package stackoverflow;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;

public class Appender
{
    private static String outFilePath = "c:\\merged.txt";

    private static boolean needLineBreakAfterAppend = true;

    public static void main(String[] args) throws IOException
    {
        if (args.length == 0) {
            // handle
            System.out.println("No input files provided, return without doing anything");
            return;
        }
        Path destFilePathObj = Paths.get(outFilePath);
        if (!Files.exists(destFilePathObj, LinkOption.NOFOLLOW_LINKS)) {
            Files.createFile(destFilePathObj);
            System.out.println("created destination file at " + outFilePath);
        } else {
            System.out.println("destination file at " + outFilePath + " was existing. Data will be appended");
        }
        Arrays.asList(args).forEach(filePathToAppend -> merge(filePathToAppend, destFilePathObj));
    }

    private static void merge(String filePathToAppend, Path destFilePathObj)
    {
        boolean fileExists = Files.exists(Paths.get(filePathToAppend));
        if (fileExists) {
            System.out.println("Input file was found at path " + filePathToAppend);
            try {
                // Appending The New Data To The Existing File
                Files.write(destFilePathObj, IOUtils.toByteArray(new FileReader(filePathToAppend)),
                    StandardOpenOption.APPEND);
                System.out.println("Done appending !");

                if (needLineBreakAfterAppend) {
                    Files.write(destFilePathObj, "\n".getBytes(), StandardOpenOption.APPEND);
                }

            } catch (IOException ioExceptionObj) {
                // handle it
            }
        } else {
            System.out.println("Input file was NOT found at path " + filePathToAppend + ". Return without appending");
            // handle it
        }
    }
}