I'm required due to previous implementation to use an InputStream, I can't use a BufferedReader.
My test bench used a BufferedReader and a while loop, like so:
while ((line = br.readLine()) != null)
However br is now required to be an InputStream (and will be renamed). Is there any way of reading in this fashion with an InputStream, or do I have to read it bytes at a time and search for the \n?
If you must read with an InputStream, then wrap it into a InputStreamReader, and then wrap this in a BufferedReader, allowing you to use your familiar BufferedReader methods. There's no need to do non-buffered input in this situation.
// assuming that you have an InputStream named inputStream
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while((line = br.readLine()) != null) {
// use line here
}
} catch (IOException e) {
e.printStackTrace();
}
Or alternatively, wrap the InputStream in a Scanner object:
try (Scanner scanner = new Scanner(inputStream)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// use line here
}
}
You can change the code like this :
public String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r;
for (r = inputStream.read(); r != '\n' && r != -1 ; r = inputStream.read()) {
baos.write(r);
}
if (r == -1 && baos.size() == 0) {
return null;
}
String lines = baos.toString("UTF-8");
return lines;
}
Maybe this example helps you..
Related
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();
}
private static void readFile1(String in, String out) throws IOException
{
FileInputStream fis = new FileInputStream(new File(in));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
if(line.length() > 0)
{
String[] words = line.split("\\s+");
for(String word : words)
{
if(word.charAt(0)=='*')
{
//System.out.println(word);
writer.write(word);
writer.newLine();
}
}
}
}
br.close();
writer.close();
fis.close();
}
}
Can someone help me with this one?
In cmd i get something like "Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range:0
The only place you seem to be referencing an index on a string is this if-statement:
if(word.charAt(0)=='*')
Change your if statement to be:
if(!word.isEmpty() && word.charAt(0)=='*')
This will first check if the word is empty and if it is not, then it will look for the proper char
UPDATE
You should add in a NULL check on word as well, just to avoid a NullPointerException
if(word != null && !word.isEmpty() && word.charAt(0)=='*')
I have searched the following popular libraries:
Guava - Fiels.readLines
nio - Files.readFirstLine or Files.readAllLines
ApacheCommons - FileUtils.readLines
All methods read whole file into memory as String collection. But that is not useful for large files with thousands of lines? Is there a simple method call to read the first n lines of a file in any of these libraries?
You could use LineNumberReader
LineNumberReader reader =
new LineNumberReader
(new InputStreamReader(new FileInputStream("/path/to/file"), "UTF-8"));
try{
String line;
while (((line = reader.readLine()) != null) && reader.getLineNumber() <= 10) {
...
}
}finally{
reader.close()
}
With Java 8 you can use Files.lines:
List<String> readFirst(final Path path, final int numLines) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines.limit(numLines).collect(toList());
}
}
Pre Java 8 you can write something yourself fairly easily:
List<String> readFirst(final Path path, final int numLines) throws IOException {
try (final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
final List<String> lines = new ArrayList<>(numLines);
int lineNum = 0;
String line;
while ((line = reader.readLine()) != null && lineNum < numLines) {
lines.add(line);
lineNum++;
}
return lines;
}
}
I do not know "ready" utility that you want but it is very simple. First create instance of BufferedReader:
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
Now read the first line:
Stirng line = reder.readLine();
Obviously you can call this method as many times as you need to read n first lines of the file, for example:
for (int i = 0; i < n; i++) {
Stirng line = reder.readLine();
// do whatever you want with the 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.
I have the following problem: I need to input a file with 12 lines. Each line consist of 8 characters. I have to output it in a file with 8 lines and 12 characters. I have to read the input line by line and output each line at the same time. So I'm not allowed to read my input first and after i read it just cut in in 8 lines with 12 characters. I'm using BufferedReader to read my file and BufferedWriter to write to my file. So by example:
Input:
12345678
qwertyui
asdfghjk
Output:
12345678qwer
tyuiasdfghjk
Edit: It's an homework assignment indeed.
BufferedWriter bufferedWriter = null;
FileReader fr;
try {
fr = new FileReader(new File(directory to file));
bufferedWriter = new BufferedWriter(new FileWriter(directory to file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
bufferedWriter.write(output);
bufferedWriter.newLine();
line = br.readLine();
}
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
This is how i read my inputfile and write to an outputfile, and it's the code I have at the moment.
Use the read method of Reader class. (FileReader is a descendant of Reader).
I'm not going to implement the whole logic but here is a skeleton to work on.
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream =
new FileReader("inputfile.txt");
outputStream =
new FileWriter("outputfile.txt");
int c;
int counter = 1;
while ((c = inputStream.read()) != -1) {
//keep a counter that will cycle for 12 characters
//check if c represents a alphabet or number, write it to file else skip
//when counter is 12 write a newline
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
The read method allows you to control how many characters to read:
See BufferedReader#read.
Same with write