简体   繁体   中英

Read a value from a text file and save it as another file

I want to create a cash memo for my project.

Now I have a little problem.

How to read a specific value from a text file and then save the value in another text file.

Example:

in data.txt file there is some values.

Item Name  : m-01

Item Brand : One Man

Item size  : XXL

Item Price : 1000

Item vat   : 15%

these are the data saved in data.txt

Now my program will ask for the item name and when I will write the item name(ex:m-01) It will just take the values 1000 ( price ) and 15 (vat) and then will save them in a new txt file data2.txt

How can I do this?

Help me please.

public class WriteOrderNumberFile {

       private static void copyFile(String sourceFileName, String
    destinationFileName, String orderNr) {

          // orderNr = "LEC##0000000073";
          BufferedReader br = null;
          PrintWriter pw = null;

          try {
             br = new BufferedReader(new FileReader(sourceFileName));
             pw = new PrintWriter(new FileWriter(destinationFileName));
             String token;
             String line;
             Scanner inFile;
             while ((line = br.readLine()) != null) {
                inFile = new Scanner(line);

                while (inFile.hasNext()) {
                   token = inFile.next();
                   if (token.equals(orderNr)) {
                      System.out.println(token);
                      pw.println(line);
                      while ((line = br.readLine()) != null) {
                         inFile = new Scanner(line);
                         while (inFile.hasNext()) {
                            token = inFile.next();
                            if (token.equals("Run")) {
                               br.close();
                               pw.close();
                               return;
                            }
                         }
                         pw.println(line);
                      }

                   }

                }

             }

             br.close();
             pw.close();
          } catch (Exception e) {
             e.printStackTrace();
          }    }

       public static void main(String[] args) {
          String sourceFileName = "D:\\Test Folder\\source.txt";
          String destinationFileName = "D:\\Test Folder\\destination.txt";
          String orderNr = "LEC##0000000064";
          copyFile(sourceFileName, destinationFileName, orderNr);    }

    }

You can simply use a couple of bash commands here:

$ egrep 'Item vat|Item Price' data.txt | cut -f2 -d:
 1000
 15%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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