我正在制作一个简单的绘画程序,并且我很难获得字符串的某个部分。 这就是问题 - 当我保存9面板图像时,它会将每个面板的RBG值存储到.txt文件中。示例:
从这里,我打电话给扫描仪来读取我们文件的行。我只需要找到将[]中的值提取到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 :(得分: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));
}