I'm trying to write a part of an String array into a String but I just stuck at a problem.
The disposal of the value of line is always like this: "status.test.status.close.name = Closed".
The only static of this value is "status." and ".name". I just want to get the part between "status." and ".name". With the code below I get this result: "status.test.status.close". My question now is, is it possible to delete parts of an array, for example: technicalNames.delete["status."];? Or does anyone has another hint how to realize it?
public void setTechnicalName(File javaFile) throws IOException {
if(javaFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(javaFile));
String line = null;
while((line = reader.readLine()) != null)
if (line.contains("In approval") || line.contains("In Approval") || line.contains("In review") || line.contains("In Review") || line.contains("Closed")){
System.out.println(line);
String[] technicalNames = line.split(".name");
String technicalName = technicalNames[0];
System.out.println(technicalName);
}
reader.close();
}
}
That is the .xml file i read out:
status.test.status.close.name = Closed
status.test.status.in.approval.name = In approval
status.test.status.in.review.name = In review
test.field.approver1 = Approver
test.field.lookupworkflow =
test.field.temp = temp
Thanks in advance!
I am assuming that you are interested in parts between status and .name. You can try this way of doing it.
public static void setTechnicalName(File javaFile) throws IOException {
if(javaFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(javaFile));
String line = null;
int statusOffet = "status.".length();
while((line = reader.readLine()) != null){
int indexOfStatus = line.indexOf("status");
int indexOfName = line.lastIndexOf(".name");
boolean isReqLine = line.contains("In approval")
|| line.contains("In Approval")
|| line.contains("In review")
|| line.contains("In Review")
|| line.contains("Closed");
if(isReqLine && indexOfStatus != -1 && indexOfName != -1){
System.out.println(line);
String stage = line.substring(indexOfStatus + statusOffet, indexOfName);
System.out.println(stage);
}
}
reader.close();
}
}
EDIT : as per comment to match format, I have included "." when calculating offset and used indexOf
When you want to split your given line into parts, you can do it similar to
final String string = "status.test.status.close.name = Closed";
final String[] split = string.substring(0, string.indexOf("=")).split("\\.");
System.out.println("split = [" + split[0] + ", " + split[1] + ", " + split[2] + ", " + split[3] + ", " + split[4] + "]"); // split = [status, test, status, close, name ]
and pick the appropriate values out of split afterwards.
Well, you have status defined twice. So assuming you are referring to the first status, and the desired result is to print out test.status.close you could do this if you knew that indexes 0 and n-1 would be not of interest:
StringBuilder builder = new StringBuilder();
String[] parts = line.split(".name")[0].split("\\.");
for(int i = 1; i < parts.length - 1; i++){
builder.append(parts[i]);
if(i < parts.length - 1){
builder.append(".");
}
System.out.println(builder.toString())
Related
Is there a more efficient way than i'm currently using, to merge two files line by line appending the line from file2 onto file1?
If file1 contains
a1
b1
c1
And file2 contains
a2
b2
c2
Then the output file should contain
a1,a2
b1,b2
c1,c2
The current combineRecords method looks like
private FileSheet combineRecords(ArrayList<FileSheet> toCombine) throws IOException
{
ArrayList<String> filepaths = new ArrayList<String>();
for (FileSheet sheetIterator : toCombine)
{
filepaths.add(sheetIterator.filepath);
}
String filepathAddition = "";
for (String s : filepaths)
{
filepathAddition = filepathAddition + s.split(".select.")[1].replace(".csv", "") + ".";
}
String outputFilepath = subsheetDirectory + fileHandle.getName().split(".csv")[0] + ".select." + filepathAddition + "csv";
Log.log("Output filepath " + outputFilepath);
long mainFileLength = toCombine.get(0).recordCount();
for (FileSheet f : toCombine)
{
int ordinal = toCombine.indexOf(f);
if (toCombine.get(ordinal).recordCount() != mainFileLength)
{
Log.log("Error : Record counts for 0 + " + ordinal);
return null;
}
}
FileSheet finalValues;
Log.log("Starting iteration streams");
BufferedWriter out = new BufferedWriter(new FileWriter(outputFilepath, false));
List<BufferedReader> streams = new ArrayList<>();
for (FileSheet j : toCombine)
{
streams.add(new BufferedReader(new FileReader(j.filepath)));
}
String finalWrite = "";
for (int i = 0; i < toCombine.get(0).recordCount(); i++)
{
for (FileSheet j : toCombine)
{
int ordinal = toCombine.indexOf(j);
finalWrite = finalWrite + streams.get(ordinal).readLine();
if (toCombine.indexOf(j) != toCombine.size() - 1)
{
finalWrite = finalWrite + ",";
}
else
{
finalWrite = finalWrite + "\n";
}
}
if (i % 1000 == 0 || i == toCombine.get(0).recordCount() - 1)
{
// out.write(finalWrite + "\n");
Files.write(Paths.get(outputFilepath),(finalWrite).getBytes(),StandardOpenOption.APPEND);
finalWrite = "";
}
}
out.close();
Log.log("Finished combineRecords");
finalValues = new FileSheet(outputFilepath,0);
return finalValues;
}
I've tried both bufferedwriters and files.write, and they have similar times to create file3, both in the 1:30 minute range, but i'm not sure if the bottleneck is at reading or writing
The sample files i'm using are currently at 36,000 records, but the actual file i'll be using is ~650,000 so taking (if it scales linearly) 1625 seconds is completely unfeasible for this operation
Edit : I've modified the code to only open files once, rather than per iteration, however i'm now getting stream closed when skipping to the nth line
I thought that by doing streams.get(ordinal).skip(i).findFirst().get(); would return a new stream instead of skipping then closing the stream
Edit 2 : Modified the code to use bufferedreaders instead of streams, and write to file every 1000 lines read, and thats determined that the bottleneck is reading, because it still takes ~1:30 to do
First of all concating string using + operator is ok when it is not under loop. But when you want to merge strings in a loop you should use StringBuilder for better performance.
Second thing which you can improve you can write to file at the end like:
StringBuilder finalWrite = new StringBuilder();
for (int i = 0; i < toCombine.get(0).recordCount(); i++)
{
for (FileSheet j : toCombine)
{
int ordinal = toCombine.indexOf(j);
finalWrite.append(streams.get(ordinal).readLine());
if (toCombine.indexOf(j) != toCombine.size() - 1)
{
finalWrite.append(",");
}
else
{
finalWrite.append("\n");
}
}
}
Files.write(Paths.get(outputFilepath), finalWrite.toString().getBytes());
I try to remove a space into a string which contains a int type value.
I read a .csv file with the scanner methode.
I use a Class to set/get the data.
I format data into the setter of the class.
Input data example:
String Pu_ht = "1 635,90";
Basic Example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "");
}
Tried example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", "");
}
Other example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll(" ", "");
}
Output data example: 1 635.90
I tried a lots of things but nothing work for my case.
Best regards
EDIT:
My code:
public void requete_pommes() throws IOException, ClassNotFoundException, SQLException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(filename));
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
List<Pommes> pomList = new ArrayList<>();
boolean firstLine = false;
while ((line = reader.readLine()) != null) {
if (!(line.equals(";;;;TOTAL HT"))) {
if (!(line.equals(";;;;"))) {
Pommes pom = new Pommes();
scanner = new Scanner(line);
scanner.useDelimiter(";");
while (scanner.hasNext()) {
String data = scanner.next();
pom.setNumero_compte("21826");
if ((index == 0)) {
pom.setReference(data);
} else if ((index == 1)) {
pom.setDesignation(data);
} else if ((index == 2)) {
pom.setQte(data);
} else if ((index == 3)) {
if(data.equals("1 635,90")){
data = data.replaceAll("\\s","");
System.err.println("data: " + data);
}
pom.setPu_ht(data);
} else if ((index == 4)) {
pom.setMontant_HT(data);
} else {
System.out.println("invalid data::" + data);
}
pom.setNumero_commande("1554");
index++;
}
index = 0;
pomList.add(pom);
requeteCorps = "(( SELECT codea FROM article WHERE tarif7 != 'O' AND tarif8 = 'O' AND pvente > 0 AND COALESCE(trim( reffou), '') != '' AND reffou = '" + pom.getReference() + "' ), " + pom.getQte() + " , " + pom.getPu_ht() + ", '" + kapiece + "', 'stomag','vendu', getnum('LCK')),";
ar.add(requeteCorps);
}
}
}
The value "1 635,90" probably stems from a locale specific format, and the "space" actually is a non-breaking space, \u00A0. This is done often to prevent in flexible width text representation a line break to happen inside a number.
s = s.replace("\u00A0", "");
String Pu_ht = "1 635,90";
System.out.println(Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", ""));
just put the above codes in main method and execute. the output will be 1635.90,then examine your codes.
My code accepts 3 arguments, first (args[0]) is the text file, second (args1) is the number of characters per line and the final argument (args[2]) is not yet implemented but is the option of the alignment (Left, Center or Justify).
Right now, I am trying to implement the left alignment and here is my code (the alignment code comes the last):
try {
System.out.println("usage: java AlignText" + args[0] + " " + args[1] + "
" + args[2]);
String[] text = FileUtil.readFile(args[0]);
int paragraphs = Integer.parseInt(args[1]);
StringBuilder builder = new StringBuilder();
for (String string : text) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(string);
}
String str = builder.toString();
StringBuilder sb = new StringBuilder();
int i = str.indexOf(" ",paragraphs);
while (i>0){
sb.append(str.substring(0, i).trim());
sb.append("\n");
str = str.substring(i);
if(str.length()>paragraphs){
i = str.indexOf(" ", paragraphs);
}
else {
i = -1;
}
}
sb.append(str.trim());
sb.toString();
//System.out.println(sb.length());
String[] lines = new String[100];
int count = 0;
int index = 0;
for(int j=0;j<sb.length();j++){
if(sb.charAt(j) == '\n') {
lines[index] = sb.substring(count,j).trim();
System.out.printf("%20s"+"\n", lines[index]);
//System.out.println("\n");
count = j;
index++;
}
}
And here is my output:
I am working on a code-editor in java and i want to know how to auto-indent using brackets (open and close) like an actual code editor .
like this 1:
Array PrincipalVar = (Var => (OtherVar => (var3 => 3,
var4 => 8,
var6 => 1)
),
Var2 => (var => 1))
Editor is a JEditorPane. I tried some code, but nothing seem to work.
I have already file contening code, and I want to Re-Indent this file.
Code I already tried :
public String indentFileTry() throws FileNotFoundException{
LinkedList<Integer> inBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String ptu = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] line = currentLine.toCharArray();
int i = 0;
while(i < line.length){ //Here I define the position of the Bracet for Indentation
if(line[i] == '('){
inBracket.addFirst(i);
}
i++;
}
if(!inBracket.isEmpty()){//here I indent with the position of the bracket and I remove the first(First In First Out)
if(!currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}else if(currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}
}
ptu += currentLine +"\n";
}
indent.close() ;
System.out.println(ptu);
return ptu;
}
If you expect automatically indentation you won't get such code. You should implement it yourself adding \n spaces (or \t) chars to format your code. JEditorPane does not understand your code logic. You (with your code parser) should define parent/child relation for lines of code you have.
One example for the case when parent/children are defined is XML. See the XMLEditorKit where nodes are indented.
For the response, What I do is easy.
I made a LinkedList, and I use it like a FILO (First in Last out) like this :
public String indentFile() throws FileNotFoundException{
LinkedList<Integer> positionBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String stringIndented = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] lineInChar = currentLine.toCharArray();
int i = 0;
int spaceadded = 0;
String space ="";
if(!positionBracket.isEmpty()){
while(spaceadded <= positionBracket.getFirst()){
spaceadded++;
space += " "; // We put same space like the last opened bracket
}
}
while(i < lineInChar.length){
if(lineInChar[i] == '('){ //If opened bracket I put the position in the top of the Filo
positionBracket.addFirst(new Integer(i));
}
if(lineInChar[i] == ')' && !countCom){
positionBracket.removeFirst(); //If closed bracket I remove the position on the top of the Filo
}
i++;
}
stringIndented += space + currentLine +"\n";
}
}
return stringIndented;
}
Can't find any help on how to do this:
I can't use .substring in the Filreader's while, it throws an exception after reading the first line.
String line = "";
BufferedReader in = new BufferedReader( new FileReader(f) );
LineNumberReader lnr = new LineNumberReader(in);
while ((line = lnr.readLine()) != null) {
System.out.println(lnr.getLineNumber() + " : " + line.substring(1, 7) +"!");
}
in.close();
lnr.close();
Glad that you have already found the answer to your problem, additionally I would like to suggest adding a range check when calling substring (at least in cases where a variable length of line is expected)
if (line.length() > 7) {
System.out.println(lnr.getLineNumber() + " : " + line.substring(1, 7) +"!");
}
else {
System.err.println("Unexpected line, minimum expected length=7 chars");
}