0

我正在尝试将我的 java 程序的输出写入文件。

用户输入了一些不应包含在文件中的数据。当程序响应时,它应该向用户输出信息,并将输出单独写入文件

从我在驱动程序类的顶部开始的示例中:

static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;

这段代码在我可能收到程序输出的每个地方:

try {
    lineFromInput = in.readLine();
    FileWrite.write(lineFromInput);
} catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
}

它的类是:

public class FileWrite {
    public static void write(String message) { 
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter("output.txt"), true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.write(message);
        out.close();
    }
}

它创建输出文件,但仅此而已。没有写入程序的任何输出。我查看了许多示例,这似乎是最简单的方法,尽管我对任何其他建议持开放态度。

谢谢!

4

3 回答 3

2

每次调用 write 都会打开和关闭文本文件。每次打开它都会被覆盖,所以我希望只有最后要写入的内容出现在文件中。

我建议从构造函数打开输出文件,然后从 close 方法关闭它。

于 2012-11-07T04:23:26.740 回答
0

我认为它应该在InputStremReader下面t的声明中使用:

static BufferedReader in= new BufferedReader(new OutputtStreamReader(System.in));
static String lineFromOutput;

作为

static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;

编辑:这很好用。请确保您通过输入控制台提供输入。另请注意,它仅读取和写入(覆盖)单行。

    public class FileWrite {
       public static void write(String message) { 
                PrintWriter out = null;
              try {
                  out = new PrintWriter(new FileWriter("output.txt"), true);
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
                out.write(message);
                out.close();
        }

       public static void main(String[] args){
           String lineFromInput;
           try {
                BufferedReader in = new BufferedReader(
                                            new InputStreamReader(System.in));
                lineFromInput = in.readLine();
                FileWrite.write(lineFromInput);
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
           }
       }
     }

编辑 2: 更新了多线输入的程序。它不是每次写入文件时打开和关闭文件的最佳方式,但我只是想让您的程序通过细微的更改即可工作。如果您需要建议以避免重复打开/关闭输出文件,请告诉我。

变化亮点:

  1. 读取行直到在输入中接收到“exit”(根据需要更改单词)
  2. append以模式打开文件。

    public class FileWrite {
       public static void write(String message) { 
                PrintWriter out = null;
              try {
                  out = new PrintWriter(new FileWriter("output.txt", true), true);
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
                out.write(message);
                out.close();
        }
    
       public static void main(String[] args){
           String lineFromInput = "";
           try {
                System.out.println("Provide the inputs in any number of lines");
                System.out.println("Type \"exit\" in new line when done");
                BufferedReader in = new BufferedReader(
                                    new InputStreamReader(System.in));
                while(!"exit".equals(lineFromInput)){
                   lineFromInput = in.readLine();
                   FileWrite.write(lineFromInput+System.lineSeparator());
                }
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
           }
       }
     }
    

EDIT3:您更新的程序Scanner用于读取输入:

        private static HashMap<Integer, Object> shapes = 
                                              new HashMap<Integer, Object>();
        static int i = 0;

        public static void main(String[] args) {
            PrintWriter output = null;
            Scanner scanner = new Scanner(System.in);
            try {
                output = new PrintWriter(new FileWriter("output.txt"), true);
            } catch (IOException e1) {
                System.err.println("You don't have accress to this file");
                System.exit(1);
            }
            String command = "";
            while(!"quit".equalsIgnoreCase(command)){
                System.out.println("Enter your Command: ");
                command = scanner.next();
                if (command.equalsIgnoreCase("create")) {
                    String type = scanner.next();
                    if (type.equalsIgnoreCase("line")) {
                        double length = scanner.nextDouble();
                        Line l = new Line(length);
                        scanner.nextLine();//flush the previous line
                        String line = scanner.nextLine();
                        output.format("%s", line);
                        shapes.put(i, l);
                        i++;
                    }else if (type.equalsIgnoreCase("circle")) {
                        double radius = scanner.nextDouble();
                        String color = scanner.next();
                        Circle c = new Circle(radius, Colors.valueOf(color));
                        scanner.nextLine();//flush the previous line
                        String line = scanner.nextLine();
                        output.format("%s", line);
                        shapes.put(i, c);
                        i++;
                    }else if (type.equals("rectangle")) {
                        double length = scanner.nextDouble();
                        double width = scanner.nextDouble();
                        String color = scanner.next();
                        Rectangle r = new Rectangle(length, width,
                        Colors.valueOf(color));
                        scanner.nextLine();//flush the previous line
                        String line = scanner.nextLine();
                        output.format("%s", line);
                        shapes.put(i, r);
                        i++;
                    }else if (type.equals("square")) {
                        double length = scanner.nextDouble();
                        String color = scanner.next();
                        Square s = new Square(length, Colors.valueOf(color));
                        scanner.nextLine();//flush the previous line
                        String line = scanner.nextLine();
                        output.format("%s", line);
                        shapes.put(i, s);
                        i++;
                    }
                }else if (command.equals("printbyperimeter")) {
                    Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
                    Arrays.sort(shapeArray);
                            System.out.println("Print in ascending order...");
                    for (int j = 0; j < shapeArray.length; j++) {
                        Shape temp = shapeArray[j];
                        if (temp.getClass().getName().equals("Line")) {
                            System.out.println("Shape: " 
                                    + temp.getClass().getName() + ", Perimeter: "
                                    + temp.getPerimeter());
                                } else {
                            System.out.println("Shape: " 
                                    + temp.getClass().getName() + ", Color: "
                                    + ((Colorable) temp).getColor()
                                    + ", Perimeter: " + temp.getPerimeter());
                                }
                            }
                }else if (command.equals("printbyarea")) {
                    Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
                    System.out.println("Print in random order...");
                    for (int j = 0; j < shapeArray.length; j++) {
                        Shape temp = shapeArray[j];
                        if (!temp.getClass().getName().equals("Line")) {
                            System.out.println("Shape: "
                                    + temp.getClass().getName() + ", Color: "
                                    + ((Colorable) temp).getColor() + ", Area: "
                                    + ((Areable) temp).getArea());
                                }
                        }
                }else if (command.equals("quit")) {
                    scanner.close();
                    System.exit(0);
                }
           }
           output.close();
        }
于 2012-11-07T03:55:29.333 回答
0

尝试使用代码。这个对我有用。您只需要更改文件路径以匹配您想要输出的位置。我在这里使用我认为是首选的 BufferedWriter。

public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromOutput;

try {
    lineFromOutput = in.readLine();
    FileWrite.write(lineFromOutput);
} catch (IOException e) {
// TODO Auto-generated catch block
 e.printStackTrace();
}



}

public static class FileWrite {
    private static void write(String message) throws IOException { 
      BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter(new File("C:\\Users\\Teresa\\Dropbox\\output.txt")));
        //Replace the above line with your path.
        out.write(message);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      out.close();
    }
}
于 2012-11-07T04:18:11.407 回答