Java : replaceAll and .split newline doesn't work - java

I am wanting to split a line up (inputLine) which is
Country: United Kingdom
City: London
so I'm using this code:
public void ReadURL() {
try {
URL url = new URL("http://api.hostip.info/get_html.php?ip=");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
String line = inputLine.replaceAll("\n", " ");
System.out.println(line);
}
in.close();
} catch ( Exception e ) {
System.err.println( e.getMessage() );
}
}
when you run the method the the output is still
Country: United Kingdom
City: London
not like it's ment to be:
Country: United Kingdom City: London
now i've tried using
\n,\\n,\r,\r\n
and
System.getProperty("line.separator")
but none of them work and using replace, split and replaceAll but nothing works.
so how do I remove the newlines to make one line of a String?
more detail: I am wanting it so I have two separate strings
String Country = "Country: United Kingdom";
and
String City = "City: London";
that would be great

You should instead of using System.out.println(line); use System.out.print(line);.
The new line is caused by the println() method which terminates the current line by writing the line separator string.

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()
Read that. readLine method will not return any carriage returns or new lines in the text and will break input by newline. So your loop does take in your entire blob of text but it reads it line by line.
You are also getting extra newlines from calling println. It will print your line as read in, add a new line, then print your blank line + newline and then your end line + newline giving you exactly the same output as your input (minus a few spaces).
You should use print instead of println.

I would advise taking a look at Guava Splitter.MapSplitter
In your case:
// input = "Country: United Kingdom\nCity: London"
final Map<String, String> split = Splitter.on('\n')
.omitEmptyStrings().trimResults().withKeyValueSeparator(": ").split(input);
// ... (use split.get("Country") or split.get("City")

Related

Java how to read a line from a text file that has multiple strings and double values?

I want to create a program that reads from a text file with three different parts and then outputs the name. E.g. text file:
vanilla 12 24
chocolate 23 20
chocolate chip 12 12
However, there is a bit of an issue on the third line, as there is a space. So far, my code works for the first two lines, but then throws a InputMismatchException on the third one. How do I make it so it reads both words from one line and then outputs it? My relevant code:
while (in.hasNext())
{
iceCreamFlavor = in.next();
iceCreamRadius = in.nextDouble();
iceCreamHeight = in.nextDouble();
out.println("Ice Cream: " + iceCreamFlavor);
}
In your input file, the separator between fields is composed of multiples spaces, no ?
if yes, you could simply use split method of String object.
You read a line.
You split it to obtain a String array.
String[] splitString = myString.split(" ");
Ther first element «0» is the String, the two others can be parsed as double
This could looks like :
try (BufferedReader br = new BufferedReader(new FileReader("path/to/the/file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] lineSplitted = line.split(" ");
String label = lineSplitted[0];
double d1 = Double.parseDouble(lineSplitted[1]);
double d2 = Double.parseDouble(lineSplitted[2]);
}
} catch (IOException e) {
e.printStackTrace();
}
You can use scanner.useDelimiter to change the delimiter or use a regular expression to parse the line.
//sets delimiter to 2 or more consecutive spaces
Scanner s = new Scanner(input).useDelimiter("(\\s){2-}");
Check the Scanner Javadoc for examples:

How to output an string of ArrayList into a new file?

Hi guys I have this sample text file in which the names of the peopel are stuck together without any spacing in between them. Is it possible for me to put this into a bufferedreader and create a ArrayList to store the values in a string and then to separate the strings by name.
Text file details:
charles_luiharry_pinkertonarlene_purcellwayne_casanova
My code:
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
List<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
FileWriter writer = new FileWriter("new_users.txt");
for (String ss : list) {
writer.write(ss);
}
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Expected output :
charles_lui
harry_pinkerton
arlene_purcell
wayne_casanova
Real output:
A duplicate of the sample file.
Just add a line separator to your writer:
writer.write(ss);
writer.write(System.lineSeparator());
If problems with your os, use System.getProperty( "line.separator" )
BufferedReader.readLine() reads and returns a line from the input which ends with \n or \r\n. It cannot detect the boundaries between the names in your input file. Better prepare the input that the names are on different lines.
It's difficult for a human to successfully separate the last-name with first-name of the next name, how can you expect a computer to do so?
Proposed solution -
Modify the sample file and add a separator(say ';') between two names.
Make a lengthy string by concatenating all the lines in the file. When concatenating remove '\n' or '\r\n' from the end of lines. (Optional - Use a StringBuffer for performance).
Split that string into an 'array of valid names'.
This can be done by calling the split(';') method on the lengthy string, with the separator as the argument.
Then, print from the array.

Java read from file line by line not reading lines correctly

I've saved a good few tweets in a text file with the following format:
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #Brazil on track to becoming the leader of #wind #energy production in Latin America http://t.co/MFJjNPxodf
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #ConceptOfficial FOLLOW ME GUYS PLEASE I LOVE YOU SO MUCH 💕BRAZIL LOVE YOU💙💚💛x16
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #JamesFenn90 plenty teams travelled far more in Brazil from their bases to each game.I'm sure eng can manage a trip to Amsterdam etc etc
Now what I look to do is read in line by line from the text file and then split the line by "TweetTextExtract: " but for some reason I keep getting an ArrayIndexOutOfBoundsException:1 error and I can't see why as every line has the "TweetTextExtract: " term. Here is the error in the console:
Country:Brazil_result.txt Date: \r\n09/19/14 #ConceptOfficial FOLLOW ME GUYS
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at WhatToThink.main(WhatToThink.java:28)
The line with this tweet has the "TweetTextExtract: " term and so does the line succeeding it. I'm not to sure why this is breaking. Here is the code:
String folderPath = "C:/Users/me/workspace/Sentiment Analysis/Good Data";
File fin = new File(folderPath + "/Brazil_result" + ".txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
//System.out.println(line);
}
br.close();
Your problem is almost surely a bad text encoding for your file. Save your file as UTF-8 (or UTF-16), then use
new InputStreamReader(fis, "UTF-8") //or UTF-16
If the encoding you use in the above constructor does not match the one of the text file, you will get gibberish and then the split won't work even on the first line.
If you want to keep the original encoding for you text file, just find out what it is and use it instead.
it actually doesn't give the exception for me when i run it.but how ever you can avoid this error by dynamically print element inside splited String.the following enhanced loop will gives you the same result ..
String[] stringline = line.split("TweetTextExtract: ");
for (String s : stringline) {
System.out.print(s);
}
System.out.println("");
and you can find your self how much element exist inside the stringline array by looking at the result.
You can use something like that:
if (line.contains("TweetTextExtract: ")){
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
}
else{
System.out.println("Line doesn't't contain \"TweetTextExtract: \"");
}

Searching a text file and printing Java

Im trying to search a csv file for a specific string. I want to print out all entries in the csv that have a specific module in the line in the csv but I cant seem to get it working. Also is it possible to print out the out in one JOptionPane window instead of a different window for every result.
Csv format
12175466, C98754, B
12141895, CS4054, B
12484665, CS3054, B
18446876, CS1044, B
User Input: CS4054
Desired Results: 12141895, CS4054, B
public static void DisplayResults() throws IOException
{
String line;
String stringToSearch = JOptionPane.showInputDialog(null, "Enter the module code ");
BufferedReader in = new BufferedReader( new FileReader("StudentResults.csv" ) );
line = in.readLine();
while (line != null)
{
if (line.startsWith(stringToSearch))
{
JOptionPane.showMessageDialog(null, line );
}
line = in.readLine();
}
in.close();
Do you mean to use startswith? Maybe try contains.
How about this?
String theAnswer="";
if (line.contains(stringToSearch)) {
theAnswer += line +"\n";
}
JOptionPane.showMessageDialog(null, theAnswer);
Your CSV file has a specific format: Values separated by a comma. So you can split each line into an array and check the second value.
String[] values = line.split(",");
if(values[1].trim().equals(stringToSearch))
JOptionPane.showMessageDialog(null, line );
EDIT:
Use the above code, when you're sure, the user always types in the second value. If you want to search over all entries use this:
for (String val : values)
if(val.trim().equals(userInput))
JOptionPane.showMessageDialog(null, line );

Replace \n in BufferedWriter.write()?

I have a String that contains for example "Name: Foo \n Date: 12/13/11 \n"
When I do BufferedWriter.write(String) to a text file it actually outputs the \n is there anyway to do a replace on \n to something that when written to a text file will signify a line break?
Here is sample code.
String input = "Name: adfasd \n AN: asdfasdf \n";
Writer textOutput = null;
File file = new File("write.txt");
textOutput = new BufferedWriter(new FileWriter(file));
textOutput.write( input );
textOutput.close();
The output would be
http://img7.imageshack.us/img7/7694/exampleve.png
Windows uses CR+LF line endings as opposed to LF endings. You should be able to use \r\n to get your desired result.
Wikipedia has an article about newlines if you want to know more.
If the string contains the text \n as opposed to the character \n, then you can do
String text = "Line 1 \\n Line2";
System.out.println(text);
System.out.println(text.replace("\\n", "\n"));
This is strange, I just tested the following code, and the resulting file displays the message on two lines :
public void test() throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("/someDir/test.txt"));
writer.write("Hello\nWorld");
writer.close();
}
Result :
Hello
World

Categories