从文件读取并存储为整数

时间:2012-04-06 19:31:56

标签: java

我正在尝试从文件中读取并将数据存储为三个整数,红色,绿色和蓝色 文件中的数据设置为:

255,0,0
0,255,0
0,0,255
0,255, 255

我已经尝试过这样做的方法,但我没有成功,任何人都可以帮助这里是迄今为止的方法的副本:

private void readColoursFromFile()  {

    int red = 128;
    int green = 128;
    int blue = 128;

    StringBuilder contents = new StringBuilder();
    String filename = "colours.txt";
     try { 
    BufferedReader reader;

   reader = new BufferedReader(new FileReader(filename));
   String str;

   while (( str = reader.readLine()) != null) {

       StringTokenizer tokenizer = new StringTokenizer(str, ",");
       String rcolour = tokenizer.nextToken(); 
       String gcolour = tokenizer.nextToken(); 
       String bcolour = tokenizer.nextToken(); 
       Integer irColour = red;
       Integer igColour = green;
       Integer ibColour = blue;
       rcolour = Integer.toString(irColour);
       gcolour = Integer.toString(ibColour);
       bcolour = Integer.toString(igColour);
     contents.append(str);
       printColourRow(red, green, blue);    
       }
   {
     reader.close();
  }
   } catch (IOException e) {
    System.out.println("error");
    e.printStackTrace();
}
}

2 个答案:

答案 0 :(得分:1)

替换

   Integer irColour = red;
   Integer igColour = green;
   Integer ibColour = blue;
   rcolour = Integer.toString(irColour);
   gcolour = Integer.toString(ibColour);
   bcolour = Integer.toString(igColour);

   red = Integer.parseInt(rcolour); 
   green = Integer.parseInt(gcolour); 
   blue = Integer.parseInt(bcolour);

答案 1 :(得分:0)

您要从此文件中设置rcolourgcolourbcolour值,但您没有对它们执行任何操作。然后将这些值设置为128.然后,您将打印一个颜色行(使用printColourRow)值128,128,128。变量redgreenblue在顶部都设置为128,永远不会更改。

你不应该打印出你正在从文件中读取的内容吗?如:

printColourRow(Integer.parseInt(rcolour),
               Integer.parseInt(gcolour),
               Integer.parseInt(bcolour));