I have a file with say 20 lines. I need to read first 3 lines, process it and write it to another file. Then give a delay of 62 seconds, read the next 3 lines and so on till the nth line. How do I go about it?. I was successful in writing first 3 lines, but confused where to put the loop for another iteration.
FileInputStream fis = new FileInputStream("C:\\Users\\Rao\\Desktop\\test.txt");
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String sCurrentLine;
int counter = 0;
while ((sCurrentLine = br.readLine()) != null) {
if (counter < 3) {
URL oracle = new URL("http://ip-api.com/json/"+sCurrentLine+"?"+"fields=isp");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
String baby= (sCurrentLine+ "\t"+ inputLine);
try {
FileWriter writer = new FileWriter("C:\\Users\\Rao\\Desktop\\output.txt", true);
writer.write(baby);
writer.write("\r\n"); // write new line
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} in.close();
}
counter++; }
TimeUnit.SECONDS.sleep(62); }
finally {
if (br != null) br.close();
}
}
}
try this. So it will sleep every third attempt.
while ((sCurrentLine = br.readLine()) != null) {
// process the data which you have read.
if ((counter % 3) == 0 ) {
TimeUnit.SECONDS.sleep(62);
}
}
Related
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
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();
}
I am unable to compile the program. The problem is in the last line "out.close". Please tell me how to rectify it and why it is causing a problem.
import java.io.*;
public class Test {
public static void main(String args[]) throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
out.close();
}
}
}
You have to declare BufferedWriter out variable outside of try-finally block, because the variables declared in try block are out of scope in finally, it's called block scope. The code should be like:
BufferedWriter out = null;
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
if (out != null)
out.close();
}
Or as it's said in comments, if Java version is 7 or above, you should use try-with-resources:
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
}
In that case, you don't need to close it manually in finally block.
Try with Resources (Java 7+). In this case, no need for close statements. Resources declared inside try will be auto closed.
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
}
You need to declare your out variable outside of yur try . . . finally block. Since try and finally are two different scopes, out is not defined in your finally block.
How can i get all the text from a website (URL:http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hydro698) and put it into a single line string, rather than more than one line, currently it will have around 20 lines give or take, but i want it to be in a single line.
Code for retreiving text:
public static void getTextFromURL() {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hydro698");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
Edit: You dont have to give me all the code, just a point in the right direction. :)
Easy, change the System.out.println to System.out.print. Done. :-D
To return a String instead, simply create a StringBuilder outside the loop, then append each line of the input to it.
Sample code to demonstrate the latter (I just realised what the OP wants, which is spaces instead of newlines):
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
if (result.length() != 0)
result.append(' ');
result.append(line);
}
return result.toString();
Hiren Patel's style of reading each character works too:
StringBuilder result = new StringBuilder();
while ((c = br.read()) != -1)
result.append(c == '\n' ? ' ' : (char) c);
return result.toString();
Retrieve the output instead of line to by character,
i.e. from while ((line = br.readLine()) != null) use while (int c != -1) read all characters and put them in a stringbuilder.
Then print the string at the end.
Edit:
use below code, it works:
public static void main(String args[]) {
URL url;
InputStream is = null;
try {
url = new URL("http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hydro698");
is = url.openStream(); // throws an IOException
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = is.read();
while (ch != -1)
{
if((char)ch != '\n')
baos.write(ch);
ch = is.read();
}
byte[] data = baos.toByteArray();
String st = new String(data);
System.out.println(st);
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
Output is:
501844,110,34581332115,30,14114403982,1,18325274,31,15814460203,14,2405287276,11,1366419761,1,67679445,1,0505401,1,70522524,1,75454208,1,0505244,1,20505816,1,40469998,1,0337042,2,155393308,5,437403072,1,0488016,1,0524106,1,0428961,1,0389021,1,0382198,1,0383592,1,0362267,1,0-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1-1,-1
Hope when u run, u will understand that output is in a single line. String st = new String(data) is holding it.
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