3

I am new to this technology. I have a text file called condition.txt which looks like this

server_state running

health_state ok

heappercent 20%

hoggingthreadcount 10

stuckthreadcount 1

I have a java file, here I want to read those data from the file and want to access those values. like in my java file I have a String variable called server_state. I want to put the value "running" in my String variable. How?

4
  • 2
    Please post your code/thoughts. Commented Feb 13, 2014 at 12:25
  • 1
    Look for FileReader and BufferedReader.. or Scanner.. Commented Feb 13, 2014 at 12:25
  • 1
    Why dont you search on google about the same topic??? Commented Feb 13, 2014 at 12:26
  • 1
    Please before asking such questions, google "How read file from Java". First answer is: stackoverflow.com/questions/4716503/… Commented Feb 13, 2014 at 12:29

3 Answers 3

3

It sounds like you want to read from a file? The Scanner class is very good for that.

You will have to format your text document in a different way, which means if you are programmatically writing the file, you need to split the 2 variables somehow. In my opinion, a comma (,) or a colon (:) are the easiest things to choose.

  • server_state:running
  • health_state:ok
  • heappercent:0.2 // Percentages will use floats/decimals
  • hoggingthreadcount:10
  • stuckthreadcount:1

    public void getProps() {
      String[] cur = new String[2];
      Scanner scanner = new Scanner("C:\Path/To/Your/File.txt");
      while(scanner.hasNextLine()) {
        cur = scanner.nextLine().split(":"); // a colon is simpler.
        if(cur[0].equalsIgnoreCase("server_state")) {
          server_state = cur[1];
        }
        if(cur[0].equalsIgnoreCase("health_state")) {
          health_state = cur[1];
        }
        if(cur[0].equalsIgnoreCase("heappercent")) {
          heappercent = Double.parseDouble(cur[1]);
        }
        if(cur[0].equalsIgnoreCase("hoggingthreadcount")) {
          hoggingthreadcount = Integer.parseInt(cur[1]);
        }
        if(cur[0].equalsIgnoreCase("stuckthreadcount")) {
          stuckthreadcount = Integer.parseInt(cur[1]);
        }
      }
      scanner.close();
    }
    

I hope this solves your problem!

Jarod.

Sign up to request clarification or add additional context in comments.

4 Comments

There is a problem . When I tried to print server_state it gives Null.
Update your question with code and output, and I will update my answer with with a fix.
yaa, your code is perfectly ok . actually its my fault to make my file in diff fashion. sorry bro .
Nah it's all good man. I'm glad I managed to help you out! :)
0

i did something similar but to read sting and integer from CSV file, the concept exactly the same

public static Countries[] readObjects() throws IOException
{

    BufferedReader br = new BufferedReader(new FileReader("d:\\countries.txt"));
    String line = "";

    Countries[] countriesArray = new Countries[32]; 

    int arrayIndex = 0;

    /***
     * Read File line by line and parse every line to Countries object and insert it into the array
     */
    while ((line = br.readLine()) != null) { 
        /***
         * Create Country object from the line
         */
        Countries country = createCountryObect(line);

        countriesArray[arrayIndex] = country;

        arrayIndex++;
    }

    br.close();

    return countriesArray;
}

/***
 * Read string and parse it into an object
 * @param line from the file 
 * @return Countries Object
 */
public static Countries createCountryObect(String line)
{
    Countries country = new Countries();

    StringTokenizer st = new StringTokenizer(line," ");

    while(st.hasMoreElements())
    {
        country.countryName = st.nextElement().toString();

        //convert country population from string to integer 
        country.countryPopulation = Integer.parseInt(st.nextElement().toString());
    }

    return country;
}

and the countries class

public class Countries {

    public String countryName;
    public int countryPopulation;

}

Comments

0

Here is a similar program I needed to write for work:

public class LogReader {

public static void main(String[] args) throws IOException 
{
    mapper("workId=\"1915900093138425722");
}


public static void mapper(String id) throws IOException
{   
    String sepText = "";
    FileWriter fileWriter;
    BufferedReader br = new BufferedReader(new FileReader(new File("Work.txt")));
    String line = "";
    while ((line = br.readLine()) != null) 
    {
        System.out.print(line);
       sepText += line.substring(0, 23) + "\n";

       int startAttIdMarker = line.indexOf(id);
       int midAttIdMarker = line.indexOf('"', startAttIdMarker + 1);
       int endAttIdMarker = line.indexOf('"', midAttIdMarker + 1 );
       sepText += "attributeSetId = " + line.substring(midAttIdMarker + 1 , endAttIdMarker) + "\n" + "\n";
       sepText += "********************************************" + "\n";
    }
    br.close();

    File newTextFile = new File("worker.txt");
    fileWriter = new FileWriter(newTextFile);
    fileWriter.write(sepText);
    fileWriter.close();
}
}

You feed a string to the function mapper and it searches for all lines with that string. It then writes those lines to a string which is in turn written to a file of it's own.

Best thing to do is play around with some sample code like this and see what happens.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.