How can i replace BufferedReader readline() by read() - java

I have this code :
try {
bufferedReader = new BufferedReader(new FileReader(new File(filePath)));
String currentLine;
int numLine = 0;
while ((currentLine = bufferedReader.readLine()) != null) {
numLine++;
for (String word : currentLine.split(" ")) {
if (!word.isEmpty() ) {
mapAllWordsPositionInFilesInFolder.computeIfAbsent(word,v -> new HashMap<>())
.computeIfAbsent(filePath, val -> new HashSet<>())
.add(numLine);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
I want change BufferedReader readline() by read() because it's more faster!
Someone can help please !

Related

Go to next line in a file with BufferedReader

I am trying to read lines from a file. For this, I am using the following code:
try {
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((line = br.readLine()) != null) {
br.readLine();
function1(line);
However, this does not move to the next line in the file.
Thank you!
Edit:
For clarity, I am making a twitter bot. The entire function looks like this:
FactGeneration.getFacts() appends a new line to the file located at /AbsoluteFilePath
private static void tweetLines() {
String tweet;
int count = 0;
while (count < 10) {
try {
try (InputStream fis = new FileInputStream(
"/AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((tweet = br.readLine()) != null) {
sendTweet(tweet);
try {
int sleepTime = 18000;
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
}
}
Edit:
The following is the working code:
while (count < numTweets) {
try {
try (InputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr)) {
//Calls static method GetFacts from the FactGeneration class.
FactGeneration.getFacts();
tweet = br.readLine();
while (tweet != null) {
//sendTweet accesses the TwitterAPI and posts the tweet.
sendTweet(tweet);
System.out.println("tweeting:" + tweet);
try {
//Pauses the thread for the given amount of time.
int sleepTime = 18000; //in milliseconds.
System.out.printf("Sleeping for %d seconds", sleepTime / 1000);
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//moves to the next line in the file.
tweet = br.readLine();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
if (count == numTweets) {
System.out.println("Tweet limit reached");
}
}
The readLine actually reads a line, it does it inside the condition of the while loop, so don't read a second time inside the loop
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
// do whatever with line
}
}
The while condition has 2 steps, this allows, that at the end, it reads null and stop looping
read a line from the file and assign the result to line
check that line is not null

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' );
}

Read large file data using buffered reader in android

hi i want to read large remote file into string using buffered reader.but i got half data of remote file.
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstream),8*1024);
StringBuilder sb = new StringBuilder(999999);
String line;
while ((line = reader.readLine()) != null) {
Log.e("Line is ",line);
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("Content: ", sb.toString());
How to get full data of remote file?
It seems there is nothing wrong with your code but you can try it this way:
private String ReceiveData(InputStream inputstream){
StringBuilder sb = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( inputstream),8*1024);
sb = new StringBuilder();
String str;
int numRead = 0;
try {
if (bufferedReader!=null) {
if (bufferedReader.ready()) {
try {
while ((numRead = bufferedReader.read()) >= 0) {
//convert asci to char and then to string
str = String.valueOf((char) numRead);
if ((str != null)&& (str.toString() != "")) {
sb.append(str);
}
if (!bufferedReader.ready()){
//no more characters to read
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//loop exited, check for null
if (sb != null) {
return sb.toString();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return "";
}
Hope I helped.

how do i get a single line from a txt file on android studio

My Code to get file content:
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.text);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
but i want only one specific line on that file to be extracted.
Use BufferedReader instead of ByteArrayOutputStream.
String readLine(int line) throws IOException {
InputStream in = getResources().openRawResource(R.raw.text);
BufferedReader r = new BufferedReader(new InputStreamReader(in));
try {
String lineStr = null;
int currentLine = 0;
while ((lineStr = r.readLine()) != null) {
if (currentLine++ == line) {
return lineStr;
}
}
} finally {
if (r != null) {
r.close();
}
}
throw new IOException("line " + line + " not found");
}

Buffered reader can't load file?

I'm working on a project for school, where I want to load questions from a file. However, Java is unable to load the file. I am sure the text file is named right and in the right direactory, but here they are:
game>src
game>out>production>game
private static void init(){
BufferedReader br = null;
ArrayList<String> strings= new ArrayList<String>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(new File("questions.txt")));
while ((sCurrentLine = br.readLine()) != null) {
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
int i = 0;
while(i < strings.size()){
String text = strings.get(i++);
int numAnswers = Integer.parseInt(strings.get(i++));
ArrayList<String> answers = new ArrayList<String>();
for (int i2 = 0; i2 < numAnswers; i2++){
answers.add(strings.get(i++));
}
questions.add(new Question(text, answers));
}
}
Try scr/questions.txt as path.
br = new BufferedReader(new FileReader(new File("src/questions.txt")));

Categories