2012-02-25 182 views
0

我正在製作一個簡單的繪畫程序,並且堅持獲取字符串的某個部分。 以下是麻煩 - 當我保存9面板圖像時,它將每個面板的RBG值存儲到.txt文件。例如:從字符串獲得值

  1. java.awt.Color中[R = 0,G = 0,B = 0]
  2. java.awt.Color中[R = 255,G = 255,B = 255]
  3. java.awt.Color [r = 255,g = 0,b = 0]
  4. java.awt.Color [r = 0,g = 0,b = 255]
  5. java.awt.Color [r = 0,g = 0,b = 0]
  6. java.awt.Color [r = 255,g = 255,b = 0]
  7. java.awt.Color [r = 255,g = 255, 0]
  8. java .awt.Color [R = 255,G = 0,B = 0]
  9. java.awt.Color中[R = 0,G = 0,B = 255]

從這裏,我稱之爲掃描儀讀取我們的文件的行。我只需要找到將[]中的值提取到String的最佳方法。我試過使用一個標記器無濟於事,仍然被卡住多餘的字符串。我試過操縱角色,但又失敗了。從我們的括號中提取數據的最佳方法是什麼?並且將單個r = xxx,b = xxx,g = xxx值存儲爲String []會更容易嗎?謝謝,這裏是我到目前爲止的來源:

import java.awt.Color; 
import java.io.*; 
import java.lang.*; 
import java.util.*; 
//when finished, organize imports (narrow down what imports were used) 

public class SaveLoad { 

private boolean tryPassed, tryPassed2; 

private Formatter x; 
//final String[] rawData; will be where the rgb raws are stored 

private Scanner xReader; 

public void save(Color[] c, String s) { 
    //s is the filename 
    int counter = c.length; 

    //Tries to create a file and, if it does, adds the data to it. 
    try{ 
     x = new Formatter(s+".txt"); 
     tryPassed = true; 
     while(counter>0) { 
      x.format("%s. %s\n", (c.length-(counter-1)), c[counter-1]); 
      counter--; 
     } 
     x.close(); 
    }catch (Exception e){ 
     e.printStackTrace(); 
     tryPassed = false; 
    } 
} 

//load will take paramaters of a filename(string); NOTE:::: make the file loaded specify an appendix (ex] .pixmap) 
//MAYBE add a load interface with a jDropdownmenu for the filetype? add parameter String filetype. 
public void load(String s, String filetype) { 
    //loads the file and, if successful, attempts to read it. 
    try{ 
     xReader = new Scanner(new File(s+filetype)); 
     tryPassed2 = true; 
    }catch(Exception e){ 
     e.printStackTrace(); 
     tryPassed2 = false; 
     System.out.println(s+filetype+" is not a valid file"); 
    } 
    while(xReader.hasNext()&&tryPassed2==true) { 
     String inBrackets = xReader.next().substring(17); 
     System.out.println(inBrackets); 
    } 
} 
} 

另外,忽略我的雜亂的符號。

+0

僅供參考,你遺漏了最重要的標籤:[tag:java]。 – 2012-02-25 22:34:01

+0

尷尬,在您發佈之前修復了大約一分鐘:感謝xP – nolasaint 2012-02-25 22:35:29

+0

其實,您的修復與我的意思相反。不要在標題中加入「(Java)」,只需在問題底部的標籤中添加[tag:java]即可。我已經解決了這兩個問題。 – 2012-02-25 22:38:03

回答

2

最好的方法是更改​​存儲格式。至少有兩個選項:

  • 逗號分隔值。每行存儲r,g,b。例如215,222,213。然後你就可以有line.split(",")使用ObjectOutputStream
+0

分離值像魅力一樣工作,謝謝! – nolasaint 2012-02-25 22:45:57

0

我會建議改變格式,以獲得值的String[]

  • 連載整個Color陣列。但如果你堅持使用一個正則表達式:

    String st = "java.awt.Color[r=0,g=0,b=0]"; 
        Pattern p = Pattern.compile("java.awt.Color\\[r=(.*),g=(.*),b=(.*)\\]"); 
    
        Matcher m = p.matcher(st); 
    
        if (m.matches()) { 
         System.out.println("r=" + m.group(1)); 
         System.out.println("g=" + m.group(2)); 
         System.out.println("b=" + m.group(3)); 
        }