Java 写入控制台和文件

Java 写入控制台和文件,java,file,file-io,Java,File,File Io,我试图让java程序的输出写入文件 用户输入一些不应包含在文件中的数据。当程序响应时,它应该向用户输出信息,并将输出写入文件 从示例中,我开始在我的驾驶课程中使用以下内容: static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static String lineFromOutput; 此代码位于我可能从程序接收输出的每个位置: try { lineFromInput = in.

我试图让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();
    }
}
它创建输出文件,但仅此而已。程序的所有输出均未写入。 我已经看了很多例子,这似乎是最简单的方法让球滚动,虽然我愿意接受任何其他建议


谢谢

我认为应该是
InputStremReader
,在下面的语句中使用单个
t

static BufferedReader in= new BufferedReader(new OutputtStreamReader(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:更新多行输入程序这不是每次编写时打开和关闭文件的最佳方式,但我只是想让您的程序进行一些小的更改。如果您需要避免重复打开/关闭输出文件的建议,请告诉我

变化亮点:

  • 读取行,直到输入中接收到“退出”(根据需要更改单词)
  • 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();
            }
    
    私有静态哈希映射形状=
    新的HashMap();
    静态int i=0;
    公共静态void main(字符串[]args){
    PrintWriter输出=null;
    扫描仪=新的扫描仪(System.in);
    试一试{
    输出=新的PrintWriter(新的FileWriter(“output.txt”),true;
    }捕获(IOE1异常){
    System.err.println(“您没有此文件的授权”);
    系统出口(1);
    }
    String命令=”;
    while(!“quit”.equalsIgnoreCase(命令)){
    System.out.println(“输入命令:”);
    command=scanner.next();
    if(command.equalsIgnoreCase(“创建”)){
    字符串类型=scanner.next();
    if(类型.equalsIgnoreCase(“行”)){
    双倍长度=scanner.nextDouble();
    l线=新线(长度);
    scanner.nextLine();//刷新上一行
    字符串行=scanner.nextLine();
    输出格式(“%s”,行);
    形状。放置(i,l);
    i++;
    }else if(类型.equalsIgnoreCase(“圆圈”)){
    双半径=scanner.nextDouble();
    字符串颜色=scanner.next();
    圆c=新圆(半径、颜色。值(颜色));
    scanner.nextLine();//刷新上一行
    字符串行=scanner.nextLine();
    输出格式(“%s”,行);
    形状。放置(i,c);
    i++;
    }else if(type.equals(“矩形”)){
    双倍长度=scanner.nextDouble();
    双倍宽度=scanner.nextDouble();
    字符串颜色=scanner.next();
    矩形r=新矩形(长度、宽度、,
    颜色(颜色)的值;
    scanner.nextLine();//刷新上一行
    字符串行=scanner.nextLine();
    输出格式(“%s”,行);
    形状。放置(i,r);
    i++;
    }else if(类型等于(“平方”)){
    双倍长度=scanner.nextDouble();
    字符串颜色=scanner.next();
    正方形s=新正方形(长度、颜色。值(颜色));
    scanner.nextLine();//刷新上一行
    字符串行=scanner.nextLine();
    输出格式(“%s”,行);
    形状。放置(i,s);
    i++;
    }
    }else if(command.equals(“PrintByPermiture”)){
    Shape[]shapeArray=shapes.values().toArray(新形状[0]);
    数组.sort(shapeArray);
    System.out.println(“按升序打印…”);
    对于(int j=0;j        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();
            }
    
    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();
        }
    }