I have a program that is reading a text file that has a list of items, creates an ArrayList consisting of the items it reads, then compares it to a few chosen words. For example, my text file contains this (without the numbering):
book
desk
food
phone
suit
and it reads each one and adds it to an ArrayList. When I tried comparing a String s = "book" to each element in the ArrayList, I find that s is not equal to anything. This is what I have in a method:
for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))
return true;
}
s.contains() doesn't work either. When I print the ArrayList, there's an additional whitespace at the end of each String element. How can I get the comparison to work when s = "book"? Why is there additional whitespace?
Use trim() to remove leading and trailing whitespace.
if (s.equals(list.get(i).trim())
return true;
}
instead of
if (s.equals(list.get(i))
return true;
}
You can use the trim() method of the String class to remove whitespaces in the start and the end of the string.
The whitespaces may be in the file but you didn't notice it. Check with an editor that there are no spaces at the end. To be more sure, check with a hexadecimal editor like hd on unix.
Also, check that the read strings do not contain the line feed character.
Well, I'm trying to replace a word by using contains() Method:
String z = tfB.getText().toString();
String show = textPane.getText().toString();
if(show.contains(z)){
// how I specify the word that were found and change it without
effecting anything with in that line
}
well what I main by that:
What I'm trying to do is get the value from the user.
then search if it found replace it with something. For example:
String x = "one two three four five";
It should set the textPane to "one two 3 four five"
or
"one two 3-three-3 four five"
could any one please tell me how to do it.
Thank you
What I'm trying to do is get the value from the user. then search if it found replace it with something.
Don't use the contains() method because you will need to search the text twice:
once to see if the text is found in the string
again to replace the text with a new string.
Instead, use the String.indexof(...) method. It will return the index of the text IF it is found in the String.
Then you should replace the text directly in the Document of the text pane, not in the String itself. So the code would be something like:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
String search = "abc...";
int offset = text.indexOf(search);
if (offset != -1)
{
textPane.setSelectionStart(offset);
textPane.setSelectionEnd(offset + search.length();
textPane.replaceSelection("123...");
}
Also, not that you get the text from the Document, not the text pane. This is to make sure the offsets are correct when you replace the text in the Document. Check out Text and New Lines for more information on why this is important.
This question already has answers here:
Java String replace not working [duplicate]
(6 answers)
Closed 9 years ago.
I got a query, please see code below:
public void readFile(String path,String pathName,int num){
try{
PrintWriter out2=new PrintWriter(new PrintWriter(path));
File a=new File(pathName);
Scanner b=new Scanner(a);
while(b.hasNextLine()){
String message=b.nextLine();
Scanner h=new Scanner(message);
while(h.hasNext()){
String f=h.next();
if (f.equals("are")){
f.replace("are","ARE");
}
}
out2.printf("%s",message);
out2.println();
.......
The file content for scanner read is
who are you?
how are you?
what is up!
However, when I run the above codes and the output to the new file are the same with the input file, it means the "are" not replaced by "ARE", I have no idea which part is wrong, please advise, thanks guys!
This line just outputs the message unchanged to the new file.
out2.printf("%s",message);
Also the loop is strange too: why do you read it word by word, and then use String.replace()? You could do it line by line, using String.replaceAll():
while(h.hasNextLine()){
String message=b.nextLine();
out2.printf("%s",message.replaceAll("(^|\\W)are(\\W|$)"," ARE "));
}
The (^|\\W)are(\\W|$) string is a regular expression, having the meaning to match all content, that starts with either being the start of the string ^, or a non-word character (\\W), the string are, and ends with a non-word character or the end of line($)...
As scanner has whitespace as the default delimiter, it might be ever better to use (^|\\s)are(\\s|$), however both these will replace the whitespace before and after "ARE" with a single space ()...
Also, keep in mind, that String.replace does not mutate the input String... You have to assign the result, or use it any other way, like pass it to a function...
String is final and immutable, which is the same.
so f.replace("are","ARE"); must be inserted into a new or not variable.
f = f.replace("are","ARE");
I do not understand why you are doing that. Here is an alternative approach:
Get a BufferedReader to read the file.
While there is data in the file, read the lines.
If line.contains("are") then line = line.replace("are","ARE")
println(line)
As to why your code did not work:
In this line, f.replace("are","ARE"); You forgot to get the output.
Make it as such: message = f.replace("are","ARE");
Another option is to use StringBuffer or StringBuilder
Strings are immutable. Therefore, you can not run the replace method on object f and expect its value to be changed since the replace method of a string object will simply return a new String object.
either use a StringBuilder instead, or use :
f = f.replace
On the other hand, StringBuilder objects are mutable. Therefore, you can run the StringBuilder version of the replace method directly on the object if you choose that route instead.
I would like to find out how to extract from this pdf(ex. image) http://postimg.org/image/ypebht5dx/
For example, I want to extract only the values in the column "TENSIONE[V]" and if it encounters a blank cell I enter the letter "X" in the output.
How could I do?
The code I used is this:
PDDocument p=PDDocument.load(new File("a.pdf"));
PDFTextStripper t=new PDFTextStripper();
System.out.println(t.getText(p));
and I get this output:
http://s23.postimg.org/wbhcrw03v/Immagine.png
These are just guidelines. Use them upon your use. This is not tested either, but help you solve your issue. If you have any question let me know.
String text = t.getText(p);
String lines[] = text.split("\\r?\\n"); // give you all the lines separated by new line
String cols[] = lines[0].split("\\s+") // gives array separated by whitespaces
// cols[0] contains pins
// clos[1] contains TENSIONE[V]
// cols[2] contains TOLLRENZA if not present then its empty
My .java file consists of a series of codes and each line is of variable size.
The .java file is shown below:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
String l;
int x=0;
}
}
Briefly, what i want to do is to scan the .java file for errors and capture the errors in a string.
I have used a diagnostic collector to capture the start and end positions of the error.
Suppose I've made an error at line 7: in x=0;
The diagnostic collector will return me the positions for example 143-145 error has occurred.
I also get the line numbers but the positions returned are relative to the whole .java file. Thus using the line numbers would be pointless as each line is of variable length and the positions are relative to the whole file. It will be difficult to compute the actual position of the error at a line.
And there is no way for me to get the end position of the last character in the previous line if there is no error at the last character of the previous line(e.g: error at line 7: previous line = line 6).
Is there a way for me to get a string by using its position(start and end) from a java file?
The easiest way is to use a RandomAccessFile.
It has a method called seek, which takes the position it should seek to:
String getStringFromFile(String fileName, long position, int length) throws IOException {
byte[] buffer = new byte[length]; // You may want to take care of multi-byte encodings here
RandomAccessFile file = new RandomAccessFile(fileName, "r");
file.seek(position);
file.readFully(buffer);
return new String(buffer); // You may want to add encoding handling here
}
Edit: You can also use a loop and read a single char at a time and use a char array instead of a byte array. It would probably be simpler for you. Use the readChar method instead of read.
Switched read to readFully to guarantee that all bytes are read.