Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a minor problem that sets me back nearly all day and I would like some input on how to solve it.
I am making a servlet for my site and I have a formatted .txt in the following form:
Name,Surname,Age
for example:
mary,jane,23
mark,thomson,25
.
.
.
etc
I want somehow to read this txt in order to pass these strings from my .txt to my database, in the corresponding fields.
Thanks in advance for any input!
Maybe this will get you started:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
String [] split = line.split(",");
String name= split[0];
String surname= split[1];
Integer age= Integer.parseInt(split[2]);
//save it to the database
}
//close the reader somewhere
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
Arraylist<String> string_array = new Arraylist<String>();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
string_array.add(sb.soString());
}
} finally {
br.close();
}
Subsequently you will separate by comma every element/line in your String Arraylist
string_array[i].split(',');
and you will proceed to any action you want with the data.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to make an HTTP request for a personal project and for some reason my request did not return the full HTML.
I don't know if I'm forgetting anything, I tried googling it but I can't find anything that helped.
URL link = new Url("https:\\www (...)");
HttpURLConnection con = (HttpURLConnection)link.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine = "";
while (in.readLine() != null){
inputLine += in.readLine();
}
in.close();
con.disconnect();
I was expecting the full HTML page, but I got part of it, like:
HTML Page:
<div>
<span>product</span>
<span>price</span>
</div>
received:
<div>
<span>product</span>
</div>
Think about what this does:
String inputLine = "";
while (in.readLine() != null){
inputLine += in.readLine();
}
You're checking if a line does not equal null, then appending the next line to the string. This means you skip every other line.
To fix this, you can assign a temporary variable the value of the nextLine() call and use that instead:
String inputLine = "";
String line = in.readLine();
while (line != null){
inputLine += line;
line = in.readLine();
}
Inline:
String inputLine = "";
String line;
while ((line = in.readLine()) != null){
inputLine += line;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter =new FileNameExtensionFilter ("Text/Java files","txt","java");
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
ArrayList<String> list = new ArrayList<>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] listArray =list.toArray(new String[list.size()]);
for (int b=0; b<listArray.length;b++) {
String[] Arra= str.split(" ");
jTextfield1.setText(Arra.get(0));
jTextfield2.setText(Arra.get(0));
Firstly, change your bufferedReader to this:
BufferedReader in = new BufferedReader(new FileReader(filename));//remove quotes around filename
You were trying to create a FileReader from a file called filename and not from the file name itself
Arra is an array but you use it as a list.
Do this instead:
if(Arra.length > 1){
jTextfield1.setText(Arra[0]);
jTextfield2.setText(Arra[1]);
}
The if statement is important because Arra might not have an index of 0 or 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know if it's possible to do this:
i've some .txt file in a directory in my filesystem
i would like to write a java code that does this:
Automatically read all the files in the directory
Give me a output
Exists some library? or it's just a code problem?
It's possible?
Thanks
Reads & prints the content
public static void main(String[] args) {
List<String> li=new TestClass().textFiles("your Directory");
for(String s:li){
try(BufferedReader br = new BufferedReader(new FileReader(s))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For getting all Text files in the Directory
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getPath());
}
}
return textFiles;
}
Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want city name from IP address using Java
is there any idea to do this ?
From Andrey link, here is how to construct the inquiry, this code will return an HTML file with all details of current IP, including city;
String IP= "123.123.123.123";
URL link = new URL("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="+IP);
BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
in.close();
UPDATE, 23 May 2013
The previous answer is ok, but it's not an API call, it reads an HTML page, that I provided previously because I didn't find any free APIs. Next is a REST API call that can be used easily and will return all the info required, it's recommended to use this one:
String ip = "2.51.255.200";
URL url = new URL("http://freegeoip.net/csv/" + ip);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
int status = connection.getResponseCode();
if (status != 200) {
return null;
}
reader = new BufferedReader(new InputStreamReader(is));
for (String line; (line = reader.readLine()) != null;) {
//this API call will return something like:
"2.51.255.200","AE","United Arab Emirates","03","Dubai","Dubai","","x-coord","y-coord","",""
// you can extract whatever you want from it
}
If your Application is deployed behind the firewall. So instead of calling a API, we can use GeoLite below is the sample code.
Download City.dat file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
File datapath = new File("GeoLiteCity.dat");
LookupService cl = new LookupService(datapath,
LookupService.GEOIP_MEMORY_CACHE
| LookupService.GEOIP_CHECK_CACHE);
String cityName = cl.getLocation(ipAddress).city;