Make a parser in a txt file

0

Good morning,

I created a * .txt file with certain paths, now I need to put those paths inside variables to call them in the application. I thought about using a parser to get this information, but I did not get any examples. If you can help me, thank you.

  

inPath = C: \ Input --- Input directory
  outPath = C: \ Output - Output directory
  inProcess = C: \ Under Processing - Processing Directory

    
asked by anonymous 08.07.2016 / 16:26

2 answers

4

Because it is a configuration file I would recommend you use a file of type .ini , but unfortunately Java does not have a default library to do this type of operation, if you agree to do so you can download the library from the address : link There is also the option of downloading it directly from Maven.

Downloaded and imported the library, you need to place a section in your file so that it is correctly interpreted with a file of type .ini . Example:

  

[cfg]
  inPath = C: \ Input; Entry directory
  outPath = C: \ Output; Outbound Directory
  inProcess = C: \ Under Processing; Processing directory

And the code would look like this:

import java.io.File;
import java.io.IOException;

import org.ini4j.Ini;
import org.ini4j.IniPreferences;
import org.ini4j.InvalidFileFormatException;

public class Teste {
    public static void main(String[] args) throws InvalidFileFormatException, IOException {
        Ini ini = new Ini(new File("meucfg.ini"));
        java.util.prefs.Preferences prefs = new IniPreferences(ini);        
        String inPath = prefs.node("cfg").get("inPath", "null").split(";")[0].trim();
        String outPath = prefs.node("cfg").get("outPath", "null").split(";")[0].trim();
        String inProcess = prefs.node("cfg").get("inProcess", "null").split(";")[0].trim();

        System.out.printf("inPath: %s\noutPath: %s\ninProcess: %s\n", inPath, outPath, inProcess);
    }    
}

Output:

  

inPath: C: \ Input
  outPath: C: \ Output
  inProcess: C: \ Under Processing

    
08.07.2016 / 16:54
0

Well, I'm not sure what your parser will be parser . Considering that you get line by line and process, I made this solution, which when processing the line already saved in the output directory, without using the inProcess directory, because I do not know if you really need it.

String inPath = "C:\Entrada\dados.txt"
String outPath = "C:\Saida\dados.txt"
FileWriter file = new FileWriter(outPath);
Scanner in = new Scanner(new FileReader(inPath));
while (in.hasNextLine()) {
     String line = in.nextLine();
     // faz processamento com vários métodos para auxiliar
     // line.split(regex);
     // line.compareTo(anotherString);
     // line.contains(string);
     // line.matches(regex);
     // ... vários outros
     System.out.println(line);
     file.write(line_processed);   // salva linha já processada
}
file.close();

Obviously this is not the only solution!

    
08.07.2016 / 17:02