Move to next element of array - java

I need the below code to move to next line and not to restart from first line again
public void actionPerformed(ActionEvent e) {
String getTextArea;
getTextArea = textArea.getText();
String[] arr = getTextArea.split("\\n");
String type = null;
String serial = null;
try {
for(String s : arr) {
if(s.isEmpty()) {
textArea_1.append("Empty line" + '\n');
s = getTextArea;
}
type = s.substring(0, 4);
serial = s.substring(5, 12);
URL url = new URL("blablabla" + type + serial);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String result;
Scanner sc;
sc = new Scanner(in);
while(sc.hasNext()) {
result = sc.next();
if (result.contains("Type:")) {
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26,30);
textArea_1.append(result + '\t');
}
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26, 29);
textArea_1.append(result + '\t');
}
}
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Here is a picture to show the result
As you see after writing empty line the first line is repeated again !

I think that instead of s = getTextArea; in the if block, you should have continue; to advance to the next element in arr.

Related

Java: Read file as long as a new date is found

I want to read the file and add each entry to an arraylist on a date. But the date should also be included.
File Example:
15.09.2002 Hello, this is the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
17.10.2020 And this ist the next entry
I tried this. But the Reader reads only the first Line
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String str_all = "";
String currLine = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
while ((currLine = br.readLine()) != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
lastLine = currLine;
liste.add(lastLine);
} else if (m.find() == false) {
str_all = currLine + " " + lastLine;
liste.set((liste.indexOf(currLine)), str_all);
}
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(0) + " "+liste.get(1);
}
}
I have solved my problem :)
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String currLine = "";
String str_all = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
currLine = br.readLine();
while (currLine != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
liste.add(currLine);
lastLine = currLine;
} else if (m.find() == false) {
liste.set((liste.size() - 1), (str_all));
lastLine = str_all;
}
currLine = br.readLine();
str_all = lastLine + currLine;
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(1) + " ");
}
}
While reading the lines, keep a "current entry".
If the line read begins with a date, then it belongs to a new entry. In this case add the current entry to the list of entries and create a new current entry consisting of the read line.
If the line did not begin with a date, just add it to the current entry.
For this to work, you need to read the first line into the current entry before the loop. And after the loop you need to add the current entry to the list of entries. This in turn only works if there is at least one line and the first line begins with a date. So handle the special case of no lines specially (use if-else). And report an error if the first line does not begin with a date.
Happy coding.

Java GUI app,server reads only first request

While making a simple Client-Server GUI app where upon the user's input dimensions of shapes are read and sent back to the server,where the method drawShape is invoked,after sending the initial request("CONNECT##" + NEW) and servers response with (DIM x,y),everything stops,client receives the (DIM x,y )prints ou "1:Draw point\n2:Draw circle\n3.Draw rectangle",and THEN IT WILL NOT SEND BACK TO THE SERVER NO MATTER WHAT I TRY TO OUTPUT,(I tried with a single word) and it did not work.
I really don't know what may be the issue,and I'm struggling with it for several days.
I parsed values,closed scanner,checked scanners,checked loops...
Why is PrintWriter refusing to send OutputStream response to the server?
This is the code:
public static final int TCP_PORT = 8000;
public SGPClientThread(Socket sock) throws IOException {
this.sock = sock;
in = new BufferedReader(new InputStreamReader(sock.getInputStream()),1);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
start();
}
ETFCanvas can = new ETFCanvas(450, 500);
public void run() {
Scanner scan = new Scanner(System.in);
System.out.println("Send new request by entering '<NEW>'");
String option = "";
option = scan.nextLine();
out.println("CONNECT##" + option);
String read = " ";
try {
read = in.readLine();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (read.startsWith("<DIM x,y>")) {
System.out.println("1:Draw point\n2:Draw circle\n3.Draw rectangle");
// SO FAR SO GOOD!
> Following code is where the problem occurs,anything I try to print out,will not be
sent to the server,it does not have to be this,you can simply try to send a
word or something simple,not working.
**int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Dimension and color of POINT:x1,y1,color");
System.out.println("Enter X: ");
x = scan.nextInt();
System.out.println("Enter Y: ");
y = scan.nextInt();
do {
try {
System.out.println(
"Enter Color value: ETFCanvas.COLOR_RED;ETFCanvas.COLOR_BLUE;ETFCanvas.COLOR_GREEN");
color = scan.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid input ");
}
scan.nextLine(); // clears the buffer
} while (color <= 0);
scan.close();
String iks = String.valueOf(x);
String ipsilon = String.valueOf(y);
String kolor = String.valueOf(color);
out.println("<POINT x,y,c>##" + iks + "##" + ipsilon + "##" + kolor);
break;**
Blockquote
And to keep it short I did not post the rest of the client thread it is just the Case 2 and 3 for drawing Circle and Rectangle,and closed Socket.
Here is my Server Thread code;
ETFCanvas can = new ETFCanvas(450, 500);
public ServerThread(Socket sock, int value) throws IOException {
this.sock = sock;
this.value = value;
// oos = new ObjectOutputStream(sock.getOutputStream());
// ois = new ObjectInputStream(sock.getInputStream());
in = new BufferedReader(new InputStreamReader(sock.getInputStream()),1);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
start();
}
#Override
public void run() {
String line = "";
//
try {
line = in.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//
if (line.startsWith("CONNECT##")) {
System.out.println("User sent request " + sock.getRemoteSocketAddress().toString() + line);
String[] content = line.split("##");
req = content[1];
if (req.equals("<NEW>")) {
out.println("<DIM x,y>");
}
} else {
System.out.println("Bad request [" + sock.getRemoteSocketAddress().toString() + "]: " + line);
> Till this part it is working like a charm,and then it will not read a clients
request for drawing
}
if (line.startsWith("<POINT x,y,c>##")) {
System.out.println("User sent request TRY" + sock.getRemoteSocketAddress().toString() + line);
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimC = dim[3];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int c = Integer.parseInt(dimC);
can.drawPoint(x, y, ETFCanvas.COLOR_RED);
} else if (line.startsWith("<CIRCLE x,y,r,boja>##")) {
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimR = dim[3];
String dimC = dim[4];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int r = Integer.parseInt(dimR);
int c = Integer.parseInt(dimC);
can.drawCircle(x, y, r, ETFCanvas.COLOR_RED);
} else if (line.startsWith("<RECTANGLE x,y,w,h,boja>##")) {
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimW = dim[3];
String dimH = dim[4];
String dimC = dim[5];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int w = Integer.parseInt(dimW);
int h = Integer.parseInt(dimH);
int c = Integer.parseInt(dimC);
can.drawRect(x, y, w, h, ETFCanvas.COLOR_RED);
;
try {
in.close();
out.close();
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
In your server code you read the first line from input but you never read next line anywhere in your code.
You should use while loop to read lines, process them and repeat:
boolean shouldProceed = true;
while (shouldProceed) {
line = in.readLine();
if (line.contains(...)) {
// do something
} else if (line.comtains(...)) {
// do something else
} else {
shouldProceed = false;
}
}

Reading text file variables and updated assigned values

I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.

Reading and modifying the text from the text file in Java

I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}

StringIndexout of range

I got an error: StringIndex out of range: -1 with error line is String anEmail = lineFromFile.substring(s+1, e). As you can see im trying to print a part of a line in an input file but i doesn't work. Can someone help me explain why?
import java.io.*;
public class Email13
{
static boolean isValidEmailCharacter(char c)
{
boolean result = false;
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||(c=='.')||(c=='-')||(c=='+'))
result = true;
return result;
}
public static void main(String[] args) throws Exception{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to start the final project.");
System.out.println();
String nameIn, nameOut, deIn, deOut;
nameIn="";
nameOut="";
deIn = "fileContainingEmails.txt";
System.out.print("Enter input filename [default:" + deIn + "]: ");
nameIn = cin.readLine();
if(nameIn.compareTo("")==0){
nameIn = deIn;
deOut = "copyPasteMyEmails.txt";
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = deOut;
}
else if(nameIn.compareTo("")>0){
deOut = nameIn;
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = nameIn;
}
fin = new BufferedReader(new FileReader(nameIn));
//Read the input file
while(true)
{
if(!fin.ready()) break;
String lineFromFile;
lineFromFile = fin.readLine();
int s, e, hasDot;
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
{
if(lineFromFile.charAt(i)=='#')
{
for(s=i;s>-1;s--)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
for(e=1; e< lineFromFile.length(); e++)
{
if(isValidEmailCharacter(lineFromFile.charAt(e))==false)
{
String anEmail = lineFromFile.substring(s+1, e);
System.out.println(anEmail);
break;
}
}
}
}
}
}
fin.close();
PrintWriter fout;
fout = new PrintWriter(new FileWriter(nameOut));
fout.close();
}
}
Suppose a line has 10 characters. So i loop goes from 0 to 9.
You then have a s loop, which goes from i to 0.
And inside that, you access `linefromFile.subString(s+1);
So when i is 9, your s loop starts at 9, and you try to access index 9+1, which is index 10, which is outside of your line.
Since Arrays are zero based indices, your lineFromFile.substring(s+1, e) is throwing an error.
for(s=i;s>-1;s--){
//lines of code
String anEmail = lineFromFile.substring(s+1, e)
This would fail for i = lineFromFile.length
as it would translate to lineFromFile[i+1] where lineFromFile[i] is the last element.

Categories

Resources