从字符串中获取值

时间:2012-02-25 22:19:08

标签: java string file token

我正在制作一个简单的绘画程序,并且我很难获得字符串的某个部分。 这就是问题 - 当我保存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,b = 0]
  8. java.awt.Color [r = 255,g = 0,b = 0]
  9. java.awt.Color [r = 0,g = 0,b = 255]
  10. 从这里,我打电话给扫描仪来读取我们文件的行。我只需要找到将[]中的值提取到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);
        }
    }
    }
    

    另外,忽略我凌乱的记谱法。

2 个答案:

答案 0 :(得分:2)

最好的方法是更改​​存储格式。至少有两个选择:

  • 逗号分隔值。在每行上存储r,g,b。例如215,222,213。然后,您可以line.split(",")获取值String[]
  • 使用Color
  • 序列化整个ObjectOutputStream数组

答案 1 :(得分:0)

我建议改变格式。但如果你坚持使用正则表达式:

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