如何将文本读取字符串插入特定变量

时间:2014-12-06 00:48:45

标签: java string text-files bufferedreader filereader

我在将简单文本文件的每一行插入到我希望它去的特定变量时遇到问题。例如,我的文本文件是这样排序的(字符串之间的文本文件中没有空格,只有这个编辑器会将它们全部放在一起)

  

达拉斯

     

78 F

     北方,每小时15英里

     

dallasimage

     

丹佛

     

29 F

     南方,每小时10英里

     

denverimage

我希望达拉斯在城市变量,78f在温度变量,等等,直到文字结束,此刻所有进入城市变量,它都从那里打印!我知道扫描仪有下一行,但从未使用它,所以我被困在这里。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Textreader {

    public static void main(String[] args) {
        try {
                        String city ="a";
                        String temp ="b";
                        String wind ="c";
                        String image = "d";
            File file = new File("load.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                              city = stringBuffer.append(line).toString();
                              stringBuffer.append("\n");
                               //city = line.toString();
                               temp = stringBuffer.append(line).toString();
                                wind  = line;
                                image = line;
                //stringBuffer.append(line);
                //stringBuffer.append("\n");
            }
            fileReader.close();
            System.out.println("Contents of file:");
                        System.out.println(city);
                        System.out.println(temp);

            //System.out.println(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您的问题伴随着您的变量" line"没有改变他的内容,并在所有变量中重复。将所有行读入集合或数组,然后继续。像这样:


    int count = 0;
    String[] lines = new String[4];
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        lines[counter++] = line;
    }

    city = lines[0];
    temp = lines[1];
    // ....

答案 1 :(得分:0)

您必须致电bufferedReader.readLine()以检索下一行。

while ((line = bufferedReader.readLine()) != null) {
    city = line;
    temp = bufferedReader.readLine();
    wind = bufferedReader.readLine();
    image = bufferedReader.readLine();
}

答案 2 :(得分:0)

查看java.util.Scanner类。你可以用它做这样的事情:

Scanner s = new Scanner(file);
Pattern pattern = Pattern.compile("(.+?)\n(.+?)\n(.+?)\n(.+?)\n");
while(s.findWithinHorizon(pattern, 0) != null) {
  MatchResult result = s.match();
  city = result.group(1); 
  temp = result.group(2);
  wind = result.group(3);
  img  = result.group(4);
  // etc. (Note that the next pass through the loop will override these variables 
  // so, unless you save the values somewhere, you will end up with them holding last
  // entry from your file once the loop is done. 
}