I have an app in which I parse a .txt file from a URL and spit out the string to the user. I want to remove the first 16 characters of the string. How can I do this?
EDIT- I want to remove 16 characters from the data I receive from my http call.
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonRetrieveMetar:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditTextAirportCode.getWindowToken(), 0);
textDisplayMetar.setText ("");
airportcode = EditTextAirportCode.getText().toString();
url = urlmetar + airportcode + ".TXT";
//Added 06-27-11 METAR code
textDisplayMetar.setText ("");
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
BufferedReader r = new BufferedReader(new
InputStreamReader(content));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
textDisplayMetar.append("\n" + total + "\n");
} catch (Exception e) {
//handle the exception !
}
break;
Thanks!
You can't modify the string itself, but you can create a substring easily enough:
line = line.substring(16);
The single-parameter overload of substring takes the whole of the rest of the string after the given start index. The two-parameter overload starts at an index specified by the first argument, and ends at an index specified by the second argument (exclusive). So to get the first three characters after "skipping" the first 16, you'd use:
line = line.substring(16, 19);
Note that you don't have to assign back to the same variable - but you need to understand that it doesn't affect the string object that you call it on. So:
String original = "hello world";
String secondPart = original.substring(6);
System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world
EDIT: If you want to remove the first 16 characters of the whole file, you want:
textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");
If you want that on a per-line basis, you want:
while ((line = r.readLine()) != null) {
total.append(line.substring(16));
}
Note that both of these may require extra validation - if you call substring(16) on a string with less than 16 characters, it will throw an exception.
Try this:
String newString = oldString.substring(16);
Related
I'm trying to write a method that:
Prints out a message (Something like: "Paste your input: ")
Waits that the user presses enter.
Reads all the lines, that got pasted and adds them up in one String.
(An empty line can be used to determine the end of the input.)
The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Ive already seen the following sites, but they all didn't help:
How to read input with multiple lines in Java
https://www.techiedelight.com/read-multi-line-input-console-java/
Make the console wait for a user input to close
Edit:
The same bug applies for:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Edit 2:
I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.
Why wouldn't use this statement?
while (!(line = buffer.readLine()).isEmpty())
In this case sending empty line will exit the loop.
Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.
I'm trying to end up with a results.txt minus any matching items, having successfully compared some string inputs against another .txt file. Been staring at this code for way too long and I can't figure out why it isn't working. New to coding so would appreciate it if I could be steered in the right direction! Maybe I need a different approach? Apologies in advance for any loud tutting noises you may make. Using Java8.
//Sending a String[] into 'searchFile', contains around 8 small strings.
//Example of input: String[]{"name1","name2","name 3", "name 4.zip"}
^ This is my exclusions list.
public static void searchFile(String[] arr, String separator)
{
StringBuilder b = new StringBuilder();
for(int i = 0; i < arr.length; i++)
{
if(i != 0) b.append(separator);
b.append(arr[i]);
String findME = arr[i];
searchInfo(MyApp.getOptionsDir()+File.separator+"file-to-search.txt",findME);
}
}
^This works fine. I'm then sending the results to 'searchInfo' and trying to match and remove any duplicate (complete, not part) strings. This is where I am currently failing. Code runs but doesn't produce my desired output. It often finds part strings rather than complete ones. I think the 'results.txt' file is being overwritten each time...but I'm not sure tbh!
file-to-search.txt contains: "name2","name.zip","name 3.zip","name 4.zip" (text file is just a single line)
public static String searchInfo(String fileName, String findME)
{
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = br.readLine()) != null)
{
if(line.startsWith("\""+findME+"\""))
{
sb.append(line);
//tried various replace options with no joy
line = line.replaceFirst(findME+"?,", "");
//then goes off with results to create a txt file
FileHandling.createFile("results.txt",line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
What i'm trying to end up with is a result file MINUS any matching complete strings (not part strings):
e.g. results.txt to end up with: "name.zip","name 3.zip"
ok with the information I have. What you can do is this
List<String> result = new ArrayList<>();
String content = FileUtils.readFileToString(file, "UTF-8");
for (String s : content.split(", ")) {
if (!s.equals(findME)) { // assuming both have string quotes added already
result.add(s);
}
}
FileUtils.write(newFile, String.join(", ", result), "UTF-8");
using apache commons file utils for ease. You may add or remove spaces after comma as per your need.
Why do i only get one entry into the map when i run this code.There is thousands of lines in the file im reading in but it only seems to be getting to the first line and stopping?
public class Details {
public Map<String, String> dictionaryWords() throws IOException{
String cvsSplitBy = ",";
Collection<String> words = new TreeSet<String>();
Map<String,String> m = new TreeMap<String,String>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("dictionary.csv")));
String line = null;
String [] word = null;
String remove = null;
String nextline = null;
String getAllLines = "-";
while ((line = br.readLine())!= null) {
if (line.startsWith("\"")) {
getAllLines = line;
while((nextline = br.readLine())!= null){
if(!nextline.startsWith("\"")){
getAllLines.concat(nextline);
}else{
}
words.add(getAllLines);
word = getAllLines.split(cvsSplitBy);
remove = word[0].replace('"', '-');
m.put(remove.toLowerCase(),Arrays.toString(word));
}
}else{
}
}
for (String key : m.keySet()) {
System.out.println(key + " " + m.get(key));}
return m;
}
Try the following code
if(!nextline.startsWith("\""))
{
getAllLines = getAllLines.concat(nextline);
}
Don't forget to reassign "getAllLines" to the return value of the .concat() function. Since Strings are immutable, the .concat() function returns a new String object, which you do not assign to anything (therefore it is lost). This leaves you with your original String still stored in "getAllLines" as if the call to .concat() was never made.
Feel Free to use the StringBuilder class and the append method, which will likely be much faster than creating new Strings via .concat() thousands of times.
Also: You do not need blank else{} statements.
In the following part of your code the nextlines (2nd ...) are lost in space. They are saved in the variable nextline and used as a parameter for getAllLines.concat. But the return value of String::concat is not assigned to anything.
...
while((nextline = br.readLine())!= null){
if(!nextline.startsWith("\"")){
getAllLines.concat(nextline);
}else{
...
I have a .txt in my website that contains a number (in this case 3) and I use this code to check whether this number is greater than or less than another number, but the code gives me this error:
03-03 16:27:43.734: E/AndroidRuntime(16318): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.downloadingprogressbar/com.example.downloadingprogressbar.MainActivity}: java.lang.NumberFormatException: Invalid int: "3
This is my code:
HttpGet httppost = new HttpGet("http://mywebsite.org/version.txt");
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String casa = new String(total.toString());
//boolean version = (casa>4);
if (Integer.parseInt(casa)>4){
risposta.setText("la tua versione รจ aggiornata");
}
else {
risposta.setText("aggiorna la tua versione");
}
I agree with Kon, your variable "casa" is containing another characters.
Try using the trim() method:
if (Integer.parseInt(casa.trim())>4){
...
...
...
but now i see that you are appending the "\n", in total variable, is this "new line" necessary?:
while ((line = r.readLine()) != null) {
total.append(line);
}
Try this to remove all whitespace that might be surrounding your number:
if (Integer.parseInt(casa.trim()) > 4){
// ...
}
I try to write a simple php file, which checks, whether a mysql value exists or not.
For this, I need to parse a simple string from json to android.
e.g: when the value exists, the string is "yes" and when it doesnt exists the string is "no".
Meanwhile I have tried a lot of "solutions", but nothing works.
To do that I usually use this:
$abfrage = "
SELECT
Something
FROM
somewhere
WHERE
This=$that"
;
$link = mysql_query($abfrage) OR die("Error:"+mysql_error());
while($line = mysql_fetch_assoc($link)){
$new=$line;
}
print(json_encode($new));
and in Android:
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
System.out.println(result);
json_data = new JSONObject(result);
String name=(json_data.getString("something"));
Log.e("pass 3", "connection success ");
}
catch(Exception e)
{
Log.e("result:", result.toString());
}
}
This works well, an the the value of the String "name" is the value of "something".
But now my question:
Is it possible to save a string in PHP and parse them to android?
This is what i got:
$abfrage = "SELECT Something FROM somewhere WHERE This = '$that' LIMIT 1";
// Proof whether the value exists or not
$read = mysql_db_query($db, $abfrage);
if (mysql_num_rows($read) == 0){
$value="no";
}
else{
$value="yes";
};
print json_encode($value);
And in JAVA:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/test.php");
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
System.out.println(""+str); //prints: yes
if(str=="yes") System.out.println("ok"); //not called
if(str=="no") System.out.println("nope"); //not called
I am not sure how you implemented it, but I assume that you execute PHP script from java code with something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample/sample.php");
HttpResponse response = httpclient.execute(httppost);
Then simply use:
String str = EntityUtils.toString(response.getEntity());
Use
Log.d("Title", "Message");
To display messages in Logcat console.
I faced this problem months before:
The problem is, that the String str, not only contains the word "yes". It also contains different letters/symbols, which are not displayed in Android/Eclipse. So you have to manually delete these letters by simply calling substring(int start, int end)
Try this:
String str = EntityUtils.toString(response.getEntity());
int number= str.length();
System.out.println("str-length"+number); //You will see not the length of 3 (for yes)
String s2= str.substring(0, 3); //short the string
System.out.println("String s2"+s2);
if(s2.equals("yes"))Log.d("Titles", str);