java - 如何从文本文件加载并执行java命令

标签 java command-line java.util.scanner java-io file-io

我是 Java 编码新手,需要一些建议。

我正在编写一个小程序,该程序根据用户控制台输入的指定在图形面板中绘制形状。 (使用扫描仪类)

例如,用户可以输入 move 100 100 将图形“笔”移动到 x,y 点, 或者可以输入 line 100 200 在两个坐标之间画一条线, 或者可以输入“circle 50”来绘制半径为 50px 的圆

我的下一个目标是包含命令“load example.txt”来加载包含一些命令的文本文件(example.txt),然后这些命令将在图形面板上执行。

我被告知最好的方法是使用

processCommandLine(String commandLine);

我已经浏览互联网很长时间了,正在寻找一些有用的信息,但到目前为止我所能找到的只是如何从文本文件中读取内容,很多都是这样的:

 Scanner reader = new Scanner(new FileInputStream("example.txt");

我知道我需要使用 Scanner 类来读取文件内容,然后(我认为使用 processCommandLine 方法)在图形面板上执行它们

到目前为止我的代码:(我已调用保存在单独文件中的所有必要的类和方法)

import java.util.Scanner;

public class Assign1 {

   public final static void main(String[] args) {
      System.out.println("Let's draw something on the screen!");

      GraphicsScreen graphics = new GraphicsScreen();

      Scanner input = new Scanner(System.in); // used to read the keyboard

      String next; // stores the next line input
      String[] one;

      do {
         System.out.print("Enter a command (\"stop\") to finish : ");
         System.out.print("Type 'help' for a list of commands ");
         next = input.nextLine();
         one = next.split(" ");

         String command = one[0];

         if (next.contains("help")) {
            System.out
                  .println("Type 'move' followed by an X and Y co-ordinate to move the graphical pointer.");
            System.out
                  .println("Type 'circle' followed by a radius value to output a circle.");
            System.out
                  .println("Type 'line' followed by an X and Y co-ordinate to draw a line.");
            System.out.println("Type 'clear' to reset the graphical canvas.");
         }

         else if (next.contains("move")) {
            int x = 0;
            int y = 0;

            x = Integer.parseInt(one[1]);
            y = Integer.parseInt(one[2]);

            graphics.moveTo(x, y);
         }

         else if (command.equalsIgnoreCase("circle")) {
            int radius = 0;
            radius = Integer.parseInt(one[1]);
            graphics.circle(radius);

         }

         else if (command.equalsIgnoreCase("line")) {
            int x = 0;
            int y = 0;

            x = Integer.parseInt(one[1]);
            y = Integer.parseInt(one[2]);

            graphics.lineTo(x, y);

         }

         else if (next.contains("clear")) {
            graphics.clear();
         }

         else {
            System.out.println("error message");
         }

      } while (next.equalsIgnoreCase("stop") == false);

      System.out
            .println("You have decided to stop entering commands. Program terminated!");

      graphics.close();
   }
}

我需要包含文本文件,例如:

move 100 100
circle 50
line 100 200

当我调用“加载 example.txt”操作时,应用程序将读取此文本文件,并通过在图形 Canvas 上绘制指定的形状来执行其中的命令。

任何帮助或指导将不胜感激,我从事 Java 编程还不到一年,并且一直在努力改进,因此欢迎任何建设性的批评。

最佳答案

所以,这是一个不错的项目,因为它向您介绍了代码重用和基本 MVC(模型- View - Controller )编程的概念。基本上,如果您认为图形上下文是您的 View ,并且您使用一组命令控制对此 View 的访问,那么您的模型显然就是命令本身。您现在要做的就是能够从替代来源提供模型,同时保持程序中的其他所有内容完好无损。

因此,您的第一个任务是创建这个可重用的“ Controller ”代码,它知道如何获取模型(命令),并使用它来影响 View (您的图形上下文)。您已经拥有所有必要的逻辑,只需将其移至您想要的函数中即可:

public static void processCommandLine(String[] commandArgs, GraphicsScreen graphics) {
   if (commandArgs == null || commandArgs.length = 0 || commandArgs[0] == null) {
      System.out.println("Null command!");
   }

   String command = commandArgs[0];

   if (command.trim().equalsIgnoreCase("move")) {
      int x = 0;
      int y = 0;

      x = Integer.parseInt(commandArgs[1]);
      y = Integer.parseInt(commandArgs[2]);

      graphics.moveTo(x, y);
   }

   else if (command.trim().equalsIgnoreCase("circle")) {
      int radius = Integer.parseInt(one[1]);
      graphics.circle(radius);

   }

   else if (command.trim().equalsIgnoreCase("line")) {
      int x = 0;
      int y = 0;

      x = Integer.parseInt(commandArgs[1]);
      y = Integer.parseInt(comamndArgs[2]);

      graphics.lineTo(x, y);
   }

   else if (command.trim().equalsIgnoreCase("clear")) {
      graphics.clear();
   }
   else {
      System.out.println("Invalid Command!");
   }
}

有了这个,您可以将命令和图形屏幕传递给单个函数,它会“渲染”该命令。现在,您想要提供访问该函数的不同方式。您的第一个访问方法是通过控制台向用户查询命令,然后执行它。但您还希望能够从文件加载多个命令并一次运行它们。因此定义一个方法来从文件中读取一堆命令:

public static List<String> getCommands(String fileName) {
   if(fileName == null) return new ArrayList<String>(0);

   File file = new File(fileName);
   if(! (file.exists() && file.canRead()) {
      System.err.println("Cannot access file! Non-existent or read access restricted");
      return new ArrayList<String>(0);
   }

   List<String> commandLines = new ArrayList<String>(32);
   Scanner scanner = new Scanner(file);
   while(scanner.hasNextLine()) {
      commandLines.add(scanner.nextLine());
   }

   scanner.close();

   return commandLines;
}

现在,您只需要更改将命令传输到渲染函数的方式,具体取决于命令源是控制台还是文件:

public final static void main(String[] args) {
   System.out.println("Let's draw something on the screen!");

   GraphicsScreen graphics = new GraphicsScreen();

   Scanner input = new Scanner(System.in); // used to read the keyboard

   String next; // stores the next line input
   String[] one;

   do {
      System.out.print("Enter a command (\"stop\") to finish : ");
      System.out.print("Type 'help' for a list of commands ");
      next = input.nextLine();
      one = next.split(" ");

      String command = one[0];

      if (command.trim().equalsIgnoreCase("help")) {
         System.out
               .println("Type 'move' followed by an X and Y co-ordinate to move the graphical pointer.");
         System.out
               .println("Type 'circle' followed by a radius value to output a circle.");
         System.out
               .println("Type 'line' followed by an X and Y co-ordinate to draw a line.");
         System.out.println("Type 'clear' to reset the graphical canvas.");
      }

      else if (command.trim().equalsIgnoreCase("load")) {
         List<String> commandLines = getCommands(one[1]);
         for (String commandLine : commandLines) {
            String[] commandArgs = commandLine.split(" ");
            processCommandLine(commandArgs, graphics);
         }
      }

      else if (command.trim().equalsIgnoreCase("stop")) {
         break;
      }

      else {
         processCommandLine(one, graphics);
      }
   } while (true);

   System.out
         .println("You have decided to stop entering commands. Program terminated!");
   graphics.close();
}

通过这些(较小的)更改,您现在可以从多个不同的源获取命令,并将这些命令呈现到您的 View 中。

关于java - 如何从文本文件加载并执行java命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611292/

相关文章:

java - 如何将文件中的 double 添加到二维数组中(Java)?

java - 为什么包资源管理器中的源文件夹不按字母顺序显示

Java:调用 native 方法给出 "Exception in thread "main"java.lang.UnsatisfiedLinkError"

python - 如何使用 Python Click 的多个命令组设置控制台脚本的入口点?

.net - 如何从powershell构建VS解决方案文件夹

node.js - 命令行应用程序的 Node 框架?

java - 为什么扫描仪功能不起作用?

java - 如何使用 Scanner 一次只读取一行整数?

Java:如果用户输入 'y' | |'Y' 测验开始 ,'n' | |'N' 测验结束,休息时显示无效。我想当用户输入以 y 或 n 开头的单词时显示无效

java - 使用 java 信号量解决读者/作者问题