How to read first five character from buffered reader? - java

I have this code
Process p =Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
BufferedReader in = new BufferedReader(read);
Running it from the terminal the first lines of oupout return the version of Busybox. If I wanted to take for example the first 5 characters as I do?

While the other answers should work well too, the following will exit and close the stream after reading five characters:
Process p = Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
StringBuilder firstFiveChars = new StringBuilder();
int ch = read.read();
while (ch != -1 && firstFiveChars.length() < 5) {
firstFiveChars.append((char)ch);
ch = read.read();
}
read.close();
a.close();
System.out.println(firstFiveChars);

try
String line = in.readLine();
if(line!=null && line.length() >5)
line = line.substring(0, 5);

Do this way
Process p;
try {
p = Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
BufferedReader in = new BufferedReader(read);
StringBuilder buffer = new StringBuilder();
String line = null;
try {
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} finally {
read.close();
in.close();
}
String result = buffer.toString().substring(0, 15);
System.out.println("Result : " + result);
} catch (Exception e) {
e.printStackTrace();
}
Output
Result : BusyBox v1.13.3

Related

How can I ignore a blank line in a srt file using Java

I have a srt file like below and I want to remove blank line : in line no 3
**
1
Line1: 00:00:55,888 --> 00:00:57,875.
Line2:Antarctica
Line3:
Line4:2
Line5:00:00:58,375 --> 00:01:01,512
Line6:An inhospitable wasteland.
**
FileInputStream fin = new FileInputStream("line.srt");
FileOutputStream fout = new FileOutputStream("m/line.srt");
int i = 0;
while(((i =fin.read()) != -1)){
if(i != 0)
fout.write((byte)i);
}
There you go. Steps:
1) FileInputStream fin = new FileInputStream("line.srt"); this is to get the file to a bufferedreader in the next step
2) BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); get the text file to a buffereader
3) PrintWriter out = new PrintWriter("newline.srt"); use a print writer to write the string of every line in the new text file
4) String line = reader.readLine(); read next line
5) while(line != null){
if (!line.trim().equals("")) { check that line is not null and that line is not empty
6) out.println(line); write line (not empty) to the output .srt file
7) line = reader.readLine(); get new line
8) out.close(); close PrintWriter in the end...
import java.io.*;
class RemoveBlankLine {
public static void main(String[] args) throws FileNotFoundException, IOException{
FileInputStream fin = new FileInputStream("line.srt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
PrintWriter out = new PrintWriter("newline.srt");
int i = 0;
String line = reader.readLine();
while(line != null){
if (!line.trim().equals("")) {
out.println(line);
}
line = reader.readLine();
}
out.close();
}
}
INPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
OUTPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
By the way, make sure you are clear when you ask your questions, because the way you state your problem I assumed Line1, Line2, etc are part of your input file, and I have prepared another solution which I had to change... Make sure you are clear and precise so that you get the proper answers !
You can try something like :
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("line.srt"));
bw = new BufferedWriter(new FileWriter("m/line.srt"));
for(String line; (line = br.readLine()) != null; ) {
if(line.trim().length() == 0) {
continue;
} else {
bw.write(line);
bw.newLine();
}
}
bw.flush();
bw.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hope this help
public static void main(String[] args) throws FileNotFoundException, IOException {
Path myPath = Paths.get("e:\\", "1.txt");
List<String> ls ;
ls = Files.readAllLines(myPath, StandardCharsets.US_ASCII);
PrintWriter out = new PrintWriter("e:\\2.txt");
for (int i = 0; i < ls.size(); i++) {
String []temp = ls.get(i).split(":");
if(temp.length>1) {
out.println(ls.get(i));
}
}
out.close();
}

BufferedReader to skip first line

I am using the following bufferedreader to read the lines of a file,
BufferedReader reader = new BufferedReader(new FileReader(somepath));
while ((line1 = reader.readLine()) != null)
{
//some code
}
Now, I want to skip reading the first line of the file and I don't want to use a counter line int lineno to keep a count of the lines.
How to do this?
You can try this
BufferedReader reader = new BufferedReader(new FileReader(somepath));
reader.readLine(); // this will read the first line
String line1=null;
while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
//some code
}
You can use the Stream skip() function, like this:
BufferedReader reader = new BufferedReader(new FileReader(somepath));
Stream<String> lines = reader.lines().skip(1);
lines.forEachOrdered(line -> {
...
});
File file = new File("path to file");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
int count = 0;
while((line = br.readLine()) != null) { // read through file line by line
if(count != 0) { // count == 0 means the first line
System.out.println("That's not the first line");
}
count++; // count increments as you read lines
}
br.close(); // do not forget to close the resources
Use a linenumberreader instead.
LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
String line1;
while ((line1 = reader.readLine()) != null)
{
if(reader.getLineNumber()==1){
continue;
}
System.out.println(line1);
}
You can create a counter that contains the value of the starting line:
private final static START_LINE = 1;
BufferedReader reader = new BufferedReader(new FileReader(somepath));
int counter=START_LINE;
while ((line1 = reader.readLine()) != null) {
if(counter>START_LINE){
//your code here
}
counter++;
}
You can do it like this:
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
String[] wordsArray;
boolean skipFirstLine = true;
while(true){
line = buf.readLine();
if ( skipFirstLine){ // skip data header
skipFirstLine = false; continue;
}
if(line == null){
break;
}else{
wordsArray = line.split("\t");
}
buf.close();

No output from Runtime.getRuntime().exec("ls")

ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?
//Works and shows the output
executeCommand("ping -c 3 " + "google.com");
//Works and shows the output
executeCommand("date");
//Does not work. No output
executeCommand("sudo ls");
//Does not work. No output
executeCommand("ls");
private void executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Output", "Output: " + output.toString());
}
I have two solutions
first solution (you need Java 7):
...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
second solution:
Process p=Runtime.getRuntime().exec("ls");
InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();
while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();

Reading txt file contents and storing in array

I have been trying to read a txt file. The txt file contains lines e.g
First Line
Second Line
Third Line
.
.
.
Now I am using following code
InputStream is = null;
try {
is = getResources().getAssets().open("myFile.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> arrayOfLines = new ArrayList<String>();
Reader reader;
//char[] buffer = new char[2048];
try {
Reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read()) != -1) {
}
}catch (Exception e) {
e.printStackTrace();
}
My question is, how can i store each line in the arrayList. Ofc We have to use a check for "/n" but how.
You could alternatively use the Scanner class.
Scanner in = new Scanner(new File("/path/to/file.txt"));
while(in.hasNextLine()) {
arrayOfLines.add(in.nextLine());
}
You don't have to worry about \n, since Scanner.nextLine() will skip the newline.
This code should work.
ArrayList<String> arrayOfLines = new ArrayList<String>();
FileInputStream fstream = new FileInputStream("myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
arrayOfLines.add(strLine);
}
This:
int n;
while ((n = reader.read()) != -1) {
}
Should probably look more like this:
String line = reader.readLine();
while (line!=null) {
arrayOfLines.add(line);
line = reader.readLine();
}
Since you are using a BufferedReader, you should be calling readLine() instead of reading into a char buffer. The Reader declaration also needs to be BufferedReader.

How to read BufferedReader faster

I want to optimize this code:
InputStream is = rp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = "";
String aux = "";
while ((aux = reader.readLine()) != null) {
text += aux;
}
The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you
Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
You can try Apache IOUtils.toString. This is what they do:
StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
sw.write(buffer, 0, n);
}
String text = sw.toString();
When BufferedReader reads from Socket, it is necessary to add bufferedReader.ready():
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb= new StringBuilder();
String line = "";
while (br.ready() && (line = br.readLine()) != null) {
sb.append(line + "\r\n");
}
String result = sb.toString();
One line solution:
String result = reader.lines().collect(joining(lineSeparator()));
Imports:
import java.io.*;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.
public String getString(BufferedReader bufferedReader) {
StringBuilder stringBuilder = new StringBuilder();
String line = null;
do {
try {
if ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
} while (line != null);
return stringBuilder.toString();
}
You can use StringBuffer
while ((aux = reader.readLine()) != null) {
stringBuffer.append(aux);
}

Categories

Resources