简体   繁体   English

如何使用BufferedReader在.txt文件中向上移动行?

[英]How to move up lines in a .txt file with BufferedReader?

Making an "assembler" program for a CS course I am enrolled in. It has functions like ADD, SET, INC (increment), and JIG. 为我注册的CS课程制作一个“汇编程序”程序。它具有ADD,SET,INC(增量)和JIG之类的功能。 Now, we are inputing a .txt file with the following layout (as example): 现在,我们输入具有以下布局的.txt文件(例如):

Keep note: A and B are just integer's that store the value throughout the program, and print out the value once it reaches the end of the text file. 请注意:A和B只是整数,它们存储整个程序中的值,并在到达文本文件末尾时打印出该值。

INC A    (increments A by 1)
SET B 5   (set's B's value to 5)
INC B
ADD A 3  (add's 3 to A's current value)
JIG B -4 (move's backward 4 lines, so back to INC A)

So what I am confused how to do is move my BufferedReader back 4 lines? 所以我很困惑如何将BufferedReader移回4行? Is there a method in BufferedReader that lets you move it to a certain index/position? BufferedReader中是否有一种方法可以让您将其移动到某个索引/位置? Otherwise, how else can I accomplish this? 否则,我还能怎么做?

The simplest thing to do is store the lines in an array or List. 最简单的方法是将行存储在数组或列表中。

List<String> lines = Files.readAllLines(Paths.get("myfile.txt"));

This will allow you to progress to any line at random. 这将允许您随机前进到任何行。

To get any line you can use lines.get(n) For example you can do 要获取任何行,您可以使用lines.get(n)例如,您可以执行

int pointer = 0;
for(boolean running = true; running && pointer < lines.size(); ) {
   String line = lines.get(pointer);
   String[] parts = line.split(" +");
   switch(part[0]) {
      case "JMP":
          pointer += Integer.parseInt(parts[1]); // jump back or forth.
          continue;
      case "HALT":
          running = false;
          break;
      // other instructions
   }
   pointer++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM