Reading an InputStream in Java - java

I'm new to Java thus the question,
I'm using the following class to read a file into a string.
public class Reader {
public static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
How can I modify the method signature of read to read a InputStream as opposed to a string.

Remove the String argument and create an argument of type InputStream. Pass this argument to the constructor of an InputStreamReader and this InputStreamReader can be passed to the constructor of your BufferedReader.
public static String readFile(InputStream is) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
.
.
.
}
Maybee you want to try a try-with-resource statement. Then you can remove the final block. It looks like this.
public static String readFile(InputStream is) throws IOException
{
try (BufferedReader br = new BufferedReader(new InputStreamReader(is)))
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
}
}

If it is not for educational purposes, don't do this manually. E.g. you could use IOUtils.toString from Apache Commons.

Related

How to read content from a text zip file?

This prints everything one one line. My original text file has different lines. How to still get the content line by line after the file is zipped? I am working on Mac.
public static void main(String[] args) throws IOException {
QuickTest mfe = new QuickTest();
ZipFile zip = new ZipFile("test.txt.zip");
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
System.out.println(entry.getName());
if (!entry.isDirectory()) {
if (FilenameUtils.getExtension(entry.getName()).equals("txt")) {
StringBuilder out = getTxtFiles(zip.getInputStream(entry));
System.out.println(out.toString());
}
}
}
System.out.println("Done");
}
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (IOException e) {
// do something, probably not a text file
e.printStackTrace();
}
return out;
}
Inside your method:
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
The following loop:
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
reads lines but the Java readLine() method does not append an end-of-line character. You'll need to add a newline (or carriage return for the Mac) to see lines.
try {
while ((line = reader.readLine()) != null) {
out.append(line);
out.append( '\n' );
}

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}

How to read a file?

private void getInput() throws IOException {
InputStream resourceAsStream = this.getClass().getResourceAsStream(
"aaa.txt");
BufferedReader br = new BufferedReader(new FileReader(
resourceAsStream.toString()));
try {
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);
} finally {
br.close();
}
}
The file aaa.txt is in the same project and it cannot be read, I have java.lang.NullPointerException when I execute that.
Only do this
BufferedReader br = new BufferedReader(new FileReader("aaa.txt"));
But put the file in the filereader instead.
Hope it helpt.

Read all data from socket

I want read all data ,synchronously , receive from client or server without readline() method in java(like readall() in c++).
I don't want use something like code below:
BufferedReader reader = new BufferedReader(new inputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
What method should i use?
If you know the size of incoming data you could use a method like :
public int read(char cbuf[], int off, int len) throws IOException;
where cbuf is Destination buffer.
Otherwise, you'll have to read lines or read bytes. Streams aren't aware of the size of incoming data. The can only sequentially read until end is reached (read method returns -1)
refer here streams doc
sth like that:
public static String readAll(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line).append("\n");
return sb.toString();
}
You could use something like this:
public static String readToEnd(InputStream in) throws IOException {
byte[] b = new byte[1024];
int n;
StringBuilder sb = new StringBuilder();
while ((n = in.read(b)) >= 0) {
sb.append(b);
}
return sb.toString();
}
try this
public static String readToEnd(InputStream in) throws IOException {
return new String(in.readAllBytes(),StandardCharsets.UTF_8);
}

java: how to use bufferedreader to read specific line

Lets say I have a text file called: data.txt (contains 2000 lines)
How do I read given specific line from: 500-1500 and then 1500-2000
and display the output of specific line?
this code will read whole files (2000 line)
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
How do I modify above code to read specific line?
I suggest java.io.LineNumberReader. It extends BufferedReader and
you can use its LineNumberReader.getLineNumber(); to get the current line number
You can also use Java 7 java.nio.file.Files.readAllLines which returns a List<String> if it suits you better
Note:
1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class
2) contents.append(System.getProperty("line.separator")) does not look nice
use contents.append(File.separator) instead
3) Catching exception seems irrelevant, I would also suggest to change your code as
public static String getContents(File aFile) throws IOException {
BufferedReader rdr = new BufferedReader(new FileReader("aFile"));
try {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
} finally {
rdr.close();
}
}
now code looks cleaner in my view. And if you are in Java 7 use try-with-resources
try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
}
so finally your code could look like
public static String[] getContents(File aFile) throws IOException {
try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String line = null; (line = rdr.readLine()) != null;) {
if (rdr.getLineNumber() >= 1500) {
sb2.append(line).append(File.pathSeparatorChar);
} else if (rdr.getLineNumber() > 500) {
sb1.append(line).append(File.pathSeparatorChar);
}
}
return new String[] { sb1.toString(), sb2.toString() };
}
}
Note that it returns 2 strings 500-1499 and 1500-2000
A slightly more cleaner solution would be to use FileUtils in apache commons.
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
Example snippet:
String line = FileUtils.readLines(aFile).get(lineNumber);
The better way is to use BufferedReader. If you want to read line 32 for example:
for(int x = 0; x < 32; x++){
buf.readLine();
}
lineThreeTwo = buf.readLine();
Now in String lineThreeTwo you have stored line 32.

Categories