I’m making a simple paint program and am stuck with getting a certain part of a string.
Here’s the trouble – When I save the 9-panel image, it stores the RBG values of each panel to a .txt file. Example:
- java.awt.Color[r=0,g=0,b=0]
- java.awt.Color[r=255,g=255,b=255]
- java.awt.Color[r=255,g=0,b=0]
- java.awt.Color[r=0,g=0,b=255]
- java.awt.Color[r=0,g=0,b=0]
- java.awt.Color[r=255,g=255,b=0]
- java.awt.Color[r=255,g=255,b=0]
- java.awt.Color[r=255,g=0,b=0]
- java.awt.Color[r=0,g=0,b=255]
From here, I call a scanner to read the lines of our file. I just need to find the best way to extract the values inside the [ ] to a String. I’ve tried using a tokenizer to no avail, still being stuck with excess Strings. I’ve tried manipulating characters but again failed. What would be the best way to go about extracting the data from our brackets? AND would it be easier to store the individual r=xxx, b=xxx, g=xxx values to a String[]? Thanks, and here is the source i have so far:
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);
}
}
}
Also, ignore my messy notations.
The best way is to change the storage format. At least two options:
r,g,bon each line. For example215,222,213. Then you can haveline.split(",")to obtain aString[]of the valuesColorarray usingObjectOutputStream