String replace and output in Java [duplicate] - java

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.

Related

Reading the file character by character in LibGDX(eclipse)?

I have a .txt file which contains following text:
111000111001
x00000010001
111110000001
I want to put this content into string so I use this method.
public void read() {
FileHandle file = Gdx.files.internal("map.txt");
String text = file.readString();
System.out.println(text.charAt(12));//Here is the problem,it's showing empty character instead of x
}
When I want to get the 12th element(x on 2nd line),it's impossible(I think there's a problem of passing to new line,but I don't know how to solve it).Can you help me please?
There's something called Carriage Return that makes extra characters appear at the end of each line (3 extra characters to be precise) when reading from a text file so to avoid getting those in your way you can use:
text = text.replaceAll("(?:\\n|\\r)", "");
And now when you try to print the 12th element you get the "x" you wanted
System.out.println(text.charAt(12)); // Prints x
Here's more info about the replaceAll() method:
Java Api: String.replaceAll()

How can I convert an entire input file into a string? [duplicate]

This question already has answers here:
How do I create a Java string from the contents of a file?
(35 answers)
Closed 6 years ago.
In Java, how would I convert an entire input file into one String?
In other words, if I have an input file "test.in":
c++
java
python
test
then I want to create a String containing "c++javapythontest".
I thought of something along the lines of
Scanner input = new Scanner(new File("test.in"));
while(input.hasNext()){
String test = test + input.nextLine();
}
but that doesn't seem to work.
Is there an efficient way to do this?
To read file contents, discarding newline chars:
String contents = Files.lines(Paths.get("test.in")).collect(Collectors.joining());
I think you needed to test for hasNextLine(), and your code's performance suffers from the creation of so many objects when you concatenate strings like that. If you changed your code to use a StringBuilder, it would run much faster.
There could be many ways to do it. One of the ways you can try is using the nio package classes. You can use the readAllBytes method of the java.nio.file.Files class to get a byte array first and then create a new String object from the byte array new String(bytes).
Read the Java Doc of this method.
Following is a sample program:
byte[] bytes= Files.readAllBytes(Paths.get(filePath));
String fileContent = new String(bytes);
Declare the String test out of the loop, then iterate filling it.
This code is a small modification to your original logic.
StringBuilder creates a mutable sequence of characters which means we just append the content to the value of StringBuilder object instead of creating a new object everytime.
In your code String test = test + input.nextLine(); was inside while loop.
Thus fresh objects of String test were created with every iteration of while loop and therefore it was not saving previous values.
String path = "test.txt";
Scanner input = new Scanner(new File(path));
StringBuilder sb = new StringBuilder();
while (input.hasNext()) {
sb.append(input.nextLine() + "\n");
}
System.out.println(sb.toString());
You can try this instead.
Its a simple one liner
String str = new String(Files.readAllBytes(Paths.get("/path/to/file")));
This reads the entire file and keeps it as String.
If you want to remove new line characters.
str.replace("\n", "");
String.join has been added in Java8 which internally uses StringBuilder
String content = String.join("", Files.readAllLines(Paths.get("test.in")));

Storing multiple values in Java without using arrays

Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;

Write text to .bat file at specified position in Java

I have a requirement to edit the .bat file with Java.
The file contains following line of text
testrunner.bat -ParId=12810 -PsysDate=2014-07-03 "C:\SOAP METHODS\DELINQ-soapui-project.xml"
Here I have a string -ParId=12810 and -PsysDate=2014-07-03, in this I need to write the new content after = sign, i.e. I need to assign different values to -ParId and -PsysDate variables.
What's wrong with rewriting the complete file?
I don't know much about regex, in fact i almost never used it, but you can utilizing regex for your problem, something like:
class RegexExample {
public static void main(String[] args) {
String input = "testrunner.bat -ParId=12810 -PsysDate=2014-07-03 'C:\\SOAP METHODS\\DELINQ-soapui-project.xml'";
input = input.replaceAll("ParId=[0-9]+","ParId=newValueID");
input = input.replaceAll("PsysDate=\\w+\\-\\w+\\-\\w+","PsysDate=newValueDate");
System.out.println(input);
}
}
I know it is not the most efficient or pretty, but you can start from there, many references found in Google though :)
If the file always contains the same text(without the parameters) you could do:
String formatstr = "testrunner.bat -ParId=%d -PsysDate=%s \"C:\SOAP METHODS\DELINQ-soapui-project.xml\"";
String output = String.format(formatstr,id,datestring);
// write output to file

Text searching with line Number Complication

EDIT:
Thanks dawww, the problem was with the Encoding, i changed it to UFT-8, and now the program works perfectly well. Just a tad slow.
I am in desperate need of help.
THE PROBLEM:
I have a TreeSet with words i took out of a text, they're all lower case and follow this regex("[^a-zA-Z]"), what i need is to compare word by word of the TreeSet with the text i took them from and get the line number each word appear, store them into and ArrayList and return.
I have the following Code:
public ArrayList<Integer> search(String word, String book) throws FileNotFoundException, IOException{
FileReader path = new FileReader(book);
LineNumberReader read = new LineNumberReader(path);
ArrayList<Integer> lines = new ArrayList<>();
String line;
for(line = read.readLine(); line != null; line = read.readLine()){
if(line.toLowerCase().contains(word)){
lines.add(read.getLineNumber());
}
}
return lines;
}
The idea is to use the search method's return as a value into a Map> (each word and the lines)
like this:
for(String s : words){
map.put(s, search(s , book));
}
words is the TreeSet with the strings i took from the text (Alice in wonderland by Lewis Carroll).
the code doesn't work, and i don't know why. The code compiles and runs but the map is empty.
To check if line contains word case insensitive, you can use Apache Commons Lang library, and specifically this method: StringUtils.containsIgnoreCase(CharSequence str, CharSequence searchStr).
This library has also other utility methods that can help, for example strip and trim are useful for cleaning Strings before operate with them.
Another problem can be with the encoding of the file. FileReader always use the platform default encoding. Try to use new InputStreamReader(new FileInputStream(filePath), <encoding>) to read from the file.
Remember contains method is case sensative.
And you are making line to lower case line.toLowerCase()
It may not be matching because of that.
Please put System.out.print statement for line.toLowerCase() and word to check it
System.out.print(line.toLowerCase()+" "+word);
And if that is the case, solution will be to lower case the word also in if condition.
if(line.toLowerCase().contains(word.toLowerCase())){
lines.add(read.getLineNumber());
}

Categories