0

I have a file that looks like this:

Dwarf remains:0
Toolkit:1
Cannonball:2
Nulodion's notes:3
Ammo mould:4
Instruction manual:5
Cannon base:6
Cannon base noted:7
Cannon stand:8
Cannon stand noted:9
Cannon barrels:10
... 

What is the easiest way to open this file, search for name and return the value of the field? I cannot use any external libraries.

What i have tried/is this ok?

    public String item(String name) throws IOException{
    String line;
    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);


    while ((line = br.readLine()) != null) {
        if(line.contains(name)){
            String[] parts = line.split(":");
            return parts[1];
        }
    }

    return null;



}
David Minesote
  • 73
  • 1
  • 10
  • What did you try so far? Any efforts? – TobiasR. Jan 10 '17 at 14:03
  • Open the file, read it line by line, use a regex to check for the name and if you found the appropriate line close the file (if needed) and return the value. Classes to look at: `File`, `FileReader`, `BufferedReader` (for easy line reading), `String` (or maybe `Pattern` and `Matcher`), etc. – Thomas Jan 10 '17 at 14:03
  • simply read the content and find what ever you want...and it would be great if you post the code you have tried or error you facing. – Iamat8 Jan 10 '17 at 14:03
  • doesn't sound too difficult, does it? – Maurice Perry Jan 10 '17 at 14:06
  • You really need to learn to use search engines. Search for "java read file" and you'll find all you need. Like http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java – Aziuth Jan 10 '17 at 14:11
  • @TobiasR. sorry added now – David Minesote Jan 10 '17 at 16:30
  • @Mohit does the thing i tried look ok? – David Minesote Jan 10 '17 at 16:31

2 Answers2

0

The task can be easily achieved using basic Java capabilities. Firstly, you need to open the the file and read its lines. It can be easily achieved with Files.lines (Path.get ("path/to/file")). Secondly, you need to iterate through all the lines returned by those instructions. If you do not know stream API, you can change value returned from Files.lines (...) from Stream to an array using String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]);. Now lines variable has all the lines from the input file.

You have to then split each line into two parts (String.split) and see whether first part equals (String.equals) what you're looking for. Then simply return the second one.

lukeg
  • 3,489
  • 3
  • 15
  • 37
0

As a followup to your code - it compiles and works ok. Be aware though, that / is not the correct path separator on Windows (\ is). You could've created the correct path using, for example: Paths.get("C:", "test.txt").toString(). Correct separator is defined as well in File.separator.

lukeg
  • 3,489
  • 3
  • 15
  • 37