I'm trying to extract device name for android using "adb devices" command ..
successfully by using this method I got that:
public void newExec() throws IOException, InterruptedException, BadLocationException{
String adbPath = "/Volumes/development/android-sdk-macosx/tools/adb";
String cmd = adbPath+" "+"devices";
Process p;
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line;
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = err.readLine()) != null) {
System.out.println(line);
}
err.close();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line=input.readLine()) != null) {
//printing in the console
System.out.println(line);
}
input.close();
}
The output is:
List of devices attached
192.168.56.101:5555 device
I tried to get only the device name out of this output which is:
192.168.56.101:5555
I used split in many ways such as:
String devices = "List of devices attached";
System.out.println(line.split(devices);
but this is not working at all!
I don't want a static way, but dynamic one. I mean if the device name changed or there are more than one listed devices I want a way to just give the device name only.
is there a way of that?
Sorry if the question is not that clear, I'm little new to Java :)
You can try below code :
The next line of output of adb devices is separated by tabs, so we have to use "\t" as argument.
List<String> deviceList = new ArrayList<String>();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.endsWith("device")) {
deviceList.add(line.split("\\t")[0]);
}
}
for (String device : deviceList) {
System.out.println(device);
}
Use the below code (Note: it only work if the string output is same every time)
String devices = "List of devices attached 192.168.56.101:5555 device";
String[] str = devices.split(' '); //spliting the string from space
System.out.println(str[4]);
Output:
192.168.56.101:5555
Hope this will help you.
I am not much familiar with Android programming but to me this sounds like a simple string parsing issue than being specific to android. Anyways, my 2 cents here. You could try parsing the lines only if it ends with
String line;
List<String> devices = new ArrayList<String>();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine())!=null){
//printing in the console
System.out.println(line);
if (!line.endsWith("device")) {
//skip if it does not ends with suffix 'device'
continue;
}
else {
//parse it now
String[] str = line.split(" ");
devices.add(str[0]);
}
}
Appears that you are using the String split() method wrong.
String devices = "List of devices attached";
System.out.println(line.split(devices);
An example of use:
String[] ss = "This is a test".split("a");
for (String s: ss )
System.out.println(s);
OUTPUT
This is
test
The parameter of split(String regex) must be a Regular Expression (regex).
Also, you could use a StringTokenizer class, or a Scanner class. These classes have more options to tokenize.
Related
i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}
In my code I have two files in my drive those two files have some text and I want to display those string in the console and also remove the repeated string and display the repeated string once rather than displaying it twice.
Code:
public class read {
public static void main(String[] args) {
try{
File file = new File("D:\\file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file1:");
String first = stringBuffer.toString();
System.out.println(first);
File file1 = new File("D:\\file2.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer1 = new StringBuffer();
String line1;
while((line1 = br1.readLine()) != null){
stringBuffer1.append(line1);
stringBuffer1.append("\n");
}
fileReader1.close();
System.out.println("Contents of file2:");
String second = stringBuffer1.toString();
System.out.println(second);
System.out.println("answer:");
System.out.println(first+second);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Output is:
answer:
hi hello
how are you
hi ya
i am fine
But I want to compare both the strings and if the same string repeated then that string should be displayed once.
Output I expect is like this:
answer:
hi hello
how are you
ya
i am fine
Where the "hi" is found in both the strings so that I need to delete the one duplicate string.
How can I do that please help.
Thanks in advance.
You can pass your lines through this method to parse out duplicate words:
// store unique previous words
static Set<String> words = new HashSet<>();
static String removeDuplicateWords(String line) {
StringJoiner sj = new StringJoiner(" ");
// split on whitespace to get distinct words
for (String word : line.split("\\s+")) {
// try to add word to the set
if (words.add(word)) {
// if the word was added (=not seen before), append to the result
sj.add(word);
}
}
return sj.toString();
}
Using Scanner, i'm not sure how to read a file with multiple lines and store it all into a String. I use a loop like :
while(file.hasNext())
{
string += file.nextLine();
}
I find that the file.hasNext method eats up all of the data in the file and so file.nextInt() doesn't have any values to find and so it returns and error. What can I do to "reset" the Scanner? I tried creating a new Scanner object but that didn't change anything. I have to run this string through a method and I have run into this problem many times. What should I do?
Maybe you should try StringBuilder.
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
// process the line.
}
}
later
String text = builder.toString();
To read the entire contents of a Scanner source into a String, set the Scanner's delimiter to the end of the file:
String contents = file.useDelimiter("\\Z").next();
I'm calling grep in java to separately count the number of a list of words in a corpus.
BufferedReader fb = new BufferedReader(
new InputStreamReader(
new FileInputStream("french.txt"), "UTF8"));
while ((l = fb.readLine()) != null){
String lpt = "\\b"+l+"\\b";
String[] args = new String[]{"grep","-ic",lpt,corpus};
Process grepCommand = Runtime.getRuntime().exec(args);
grep.waitFor()
}
BufferedReader grepInput = new BufferedReader(new InputStreamReader(grep.getInputStream()));
int tmp = Integer.parseInt(grepInput.readLine());
System.out.println(l+"\t"+tmp);
This works well for my English word-list and corpus. But I also have a French word list and corpus. It doesn't work for french and a sample output on java console looks like this:
� bord 0
� c�t� 0
correct form: "à bord" and "à côté".
Now my question is: where is the problem? Should I fix my java code, or it's a grep issue?
If so how do I fix it. (I also can't see french characters on my terminal correctly even though I changed the encoding to UTF-8).
The problem is in your design. Do not call grep from java. Use pure java implementation instead: read file line by line and implement your own "grep" using pure java API.
But seriously I believe that the problem is in your shell. Did you try to run grep manually and filter French characters? I believe it will not work for you. It depends on your shell configuration and therefore depends on platform. Java can provide platform independent solution. To achieve this you should avoid as much as it is possible using non-pure-java techniques including executing command line utilities.
BTW code that reads line-by-line your file and uses String.contains() or pattern matching for lines filtering even shorter than code that runs grep.
I would suggest that you read the file line by line then call split on the word boundary to get the number of words.
public static void main(String[] args) throws IOException {
final File file = new File("myFile");
try (final BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
final String[] words = line.split("\\b");
System.out.println(words.length + " words in line \"" + line + "\".");
}
}
}
This avoids calling grep from you program.
The odd characters you are getting may well be do to with using the wrong encoding. Are you sure your file is in "UTF-8"?
EDIT
OP wants to read one file line-by-line and then search for occurrences of the read line in another file.
This can still be done more easily using java. Depending on how big your other file is you can either read it into memory first and search it or search it line-by-line also
A simple example reading the file into memory:
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
final File corpusFile = new File("corpus");
final String corpusFileContent = readFileToString(corpusFile);
final File file = new File("myEngramFile");
try (final BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
final int matches = countOccurencesOf(line, corpusFileContent);
};
}
}
private static String readFileToString(final File file) throws IOException {
final StringBuilder stringBuilder = new StringBuilder();
try (final FileChannel fc = new RandomAccessFile(file, "r").getChannel()) {
final ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
final CharsetDecoder charsetDecoder = Charset.forName("UTF-8").newDecoder();
while (fc.read(byteBuffer) > 0) {
byteBuffer.flip();
stringBuilder.append(charsetDecoder.decode(byteBuffer));
byteBuffer.reset();
}
}
return stringBuilder.toString();
}
private static int countOccurencesOf(final String countMatchesOf, final String inString) {
final Matcher matcher = Pattern.compile("\\b" + countMatchesOf + "\\b").matcher(inString);
int count = 0;
while (matcher.find()) {
++count;
}
return count;
}
This should work fine if your "corpus" file is less than a hundred megabytes or so. Any bigger and you will want to change the "countOccurencesOf" method to something like this
private static int countOccurencesOf(final String countMatchesOf, final File inFile) throws IOException {
final Pattern pattern = Pattern.compile("\\b" + countMatchesOf + "\\b");
int count = 0;
try (final BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
final Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
++count;
}
};
}
return count;
}
Now you would just pass your "File" object into the method rather than the stringified file.
Note that the streaming approach reads files line-by-line and hence drops the linebreaks, you need to add them back before parsing the String if your Pattern relies on them being there.
I need to read alot of files and insert the data into Ms sql.
Got a file, it looks the texts are separated by //t.
Split does not do the job, I have even tried with "//s+" as you can see in the code below
public void InsetIntoCustomers(final File _file, final Connection _conn)
{
conn = _conn;
try
{
FileInputStream fs = new FileInputStream(_file);
DataInputStream in = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//String strline contains readline() from BufferedReader
String strline;
while((strline = br.readLine()) != null)
{
if(!strline.contains("#"))
{
String[] test = strline.split("//s+");
if((tempid = sNet.chkSharednet(_conn, test[0] )) != 0)
{
// do something
}
}
}
// close BufferedReader
br.close();
}
I need to know where in my String[] the data is placed in a file with 500k lines. But my Test[] get length 1 and all data from readline are on place 0.
Do I use split wrong ?
Or are there other places I need to look?:
// Mir
haha - Thank you so much - why the hell didnt I see that myself.
yeah ofc. iam using \s+ at all other files.
but thank for pointing it out.
The correct regex is \\s+, with back-shashes instead of forward-slashes.
You could have still tried with \\t