如何在Java中读取文本文件并访问这些值

3

我对这项技术还不熟悉。我有一个名为condition.txt的文本文件,内容如下:

server_state running

health_state ok

heappercent 20%

hoggingthreadcount 10

stuckthreadcount 1

我有一个Java文件,现在想要从文件中读取这些数据并访问这些值。比如说,在我的Java文件中,我有一个名为server_state的字符串变量。我想将值“running”放入我的字符串变量中。该怎么做呢?


2
请发布您的代码/想法。 - Maroun
1
寻找FileReader和BufferedReader..或Scanner.. - TheLostMind
1
为什么不在谷歌上搜索同样的主题呢? - AJ.
1
在提问此类问题之前,请先使用谷歌搜索“如何从Java中读取文件”。第一个答案是:https://dev59.com/22445IYBdhLWcg3wwcug。 - Manuel Selva
3个回答

3

看起来你想从文件中读取内容?在这种情况下,Scanner类非常适合使用。

你需要以不同的方式格式化文本文档,这意味着如果你是通过编程方式写入文件,则需要以某种方式拆分这两个变量。我认为逗号(,)或冒号(:)是最容易选择的方式。

  • 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();
    }
    
我希望这能解决你的问题! Jarod.

有一个问题。当我尝试打印server_state时它会返回Null。 - user3061048
请在您的问题中附上代码和输出,我会用修复方法更新我的回答。 - TheBrenny
你的代码完全没问题。其实是我的错,我把文件弄成了不同的格式。对不起兄弟。 - user3061048
没事,伙计。我很高兴能帮到你! :) - TheBrenny

0
我做过类似的事情,但是从CSV文件中读取字符串和整数,概念完全相同。
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;
}

以及国家类

public class Countries {

    public String countryName;
    public int countryPopulation;

}

0

这是我在工作中需要编写的类似程序:

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();
}
}

你将一个字符串传递给函数映射器,它会搜索所有包含该字符串的行。然后将这些行写入一个字符串,最终写入一个文件中。
最好的方法是尝试一些类似这样的示例代码,并观察发生了什么。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接