如何将错误从控制台复制到文件以及包含代码的位置以及代码是什么?

时间:2014-11-29 05:59:42

标签: java eclipse

import java.io.BufferedReader;

import java.io.Console;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.InputStreamReader;

import java.nio.file.Paths;

公共类日志文件 {

public static void main(String [] args)抛出FileNotFoundException {

尝试
     {

String [] commands = {" cmd"," / c"," dir / p"};

final File outputFile = Paths.get(" c://users//sihi//logfile.txt",args).toFile();

final ProcessBuilder pb = new PrrocessBuilder(commands).redirectOutput(outputFile).redirectErrorStream(true);

        final Process p = pb.start();

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = reader.readLine();

            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String Error;
            while ((Error = stdError.readLine()) != null) {
                System.out.println(Error);
            }
            while ((Error = stdInput.readLine()) != null) {
                System.out.println(Error);
            }
        } catch (Exception e) {
            e.printStackTrace();
     } } }

1 个答案:

答案 0 :(得分:0)

您使用ProcessBuilder并已将输出重定向到文件:

final File outputFile = Paths.get("c://users//sihi//logfile.txt", args).toFile();

final ProcessBuilder pb = new ProcessBuilder(commands)
    .redirectOutput(outputFile).redirectErrorStream(true);

请阅读outputFile ...

另外,您使用Java 7,所以:

for (final String line: Files.readAllLines(yourPath, StandardCharsets.UTF_8))
    System.out.println(line);

由于这是Java 7,而不是为输出创建File,而是创建Path并使用.toFile()

final Path path = Paths.get("c://users//sihi//logfile.txt", args);

final ProcessBuilder pb = new ProcessBuilder(commands)
    .redirectOutput(path.toFile()).redirectErrorStream(true);

final Process p = pb.start();
p.waitFor(); // throws InterruptedException

for (final String line: Files.readAllLines(path, StandardCharsets.UTF_8))
    System.out.println(line);