Write URL data to file is empty - java

I am trying to get data from URL and write it to a file, and I got the data from the URL but the file is empty, and below my code:
public class LiveRead {
public static void main(String[] args){
try {
URL u = new URL("http://quotes.rest/qod.json?category=life");
HttpURLConnection hr = (HttpURLConnection) u.openConnection();
if (hr.getResponseCode() == 200){
InputStream im = hr.getInputStream();
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(im));
FileOutputStream fo = new FileOutputStream("/Users/macos/Desktop/json");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));
String line = br.readLine();
while (line != null){
System.out.println(line);
bw.write(line);
bw.newLine();
line = br.readLine();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
and when I open /Users/macos/Desktop/json, that file is empty. What's wrong and how to resolve it?

You should explicitly flush and close your writer, and not assume Java will do it for you when the program terminates:
bw.flush();
bw.close();

Related

Reading bytes from a file

I am reading from a ".264" file using code below.
public static void main (String[] args) throws IOException
{
BufferedReader br = null;try {
String sCurrentLine;
br = new BufferedReader(new InputStreamReader(new FileInputStream("test.264"),"ISO-8859-1"));
StringBuffer stringBuffer = new StringBuffer();
while ((sCurrentLine = br.readLine()) != null) {
stringBuffer.append(sCurrentLine);
}
String tempdec = new String(asciiToHex(stringBuffer.toString()));
System.out.println(tempdec);
String asciiEquivalent = hexToASCII(tempdec);
BufferedWriter xx = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:/Users/Administrator/Desktop/yuvplayer-2.3/video dinalized/testret.264"),"ISO-8859-1"));
xx.write(asciiEquivalent);
xx.close();
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Opening input and output file in HEX Editor show me some missing values, e.g. 0d (see pictures attached).
Any solution to fix this?
Lose InputStreamReader and BufferedReader, just use FileInputStream on its own.
No character encoding, no line endings, just bytes.
Its Javadoc page is here, that should be all you need.
Tip if you want to read the entire file at once: File.length(), as in
File file = new File("test.264");
byte[] buf = new byte[(int)file.length()];
// Use buf in InputStream.read()

Reading a variable number of lines from a file

I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer

Writing multiple queries from a test file

public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.

Modify the content of a file using Java

I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.
But its deleting the all content of the file.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public statc void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I would start with closing reader, and flushing writer:
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The accepted answer is great. However, there is an easier way to replace content in a file using Apache's commons-io library (commons-io-2.4.jar - you can use any latest versions)
private void update() throws IOException{
File file = new File("myPath/myFile.txt");
String fileContext = FileUtils.readFileToString(file);
fileContext = fileContext.replaceAll("_PLACEHOLDER_", "VALUE-TO-BE-REPLACED");
FileUtils.write(file, fileContext);
}
Note: Thrown IOException needs to be caught and handled by the application accordingly.
Read + write to the same file simulatenously is not ok.
EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.
Make sure to:
close any stream when you no longer need them
In particular before reopening it for writing.
truncate the file, to make sure it shrinks if you write less than it had.
then write the output
write individual lines, don't rely on toString.
flush and close when you are finished writing!
If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!
I can see three problems.
First you are writing to out which I assume is System.out, not an output stream to the file.
Second, if you do write to an output stream to the file, you need to close it.
Third, the toString() method on an ArrayList isn't going to write the file like you are expecting. Loop over the list and write each String one at a time. Ask yourself whether you need to write newline characters as well.
The accepted answer is slightly wrong. Here's the correct code.
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
}
out.close();
catch (Exception ex) {
ex.printStackTrace();
}
}

Java appending new file's data to old file

In the first step am creating a file say test1.txt and adding records to it, and the rest records to test2.txt. Now i want to append the records of test2.txt to test1.txt. How to append them to test1.txt. The reason am dividing the files is i have a List with about 53K records, which am unable to write in a single file, as the buffer writer is closing as its reaching 52K.
The function am using for creating a single file is
public void exportApprovedList() throws IOException {
File approvedWhiteListFile = new File("/var/tmp/livecron/dictionary.common");
BufferedWriter bw = new BufferedWriter(new FileWriter(approvedWhiteListFile));
if (approvedWhiteListFile.exists()) {
List<WhiteListTerm> approvedWhiteList = whiteListBO.getByStatus("APPROVED");
for (WhiteListTerm whiteList : approvedWhiteList) {
bw.write(whiteList.getTerm() + "|" +
whiteListCategoryBO.getById(whiteList.getCategoryId()).getCategoryname());
bw.newLine();
}
}
bw.close();
}
try this....
import java.io.*;
public class FileReadWrite {
public void writeFile(String sorcefile)
{
try{
FileInputStream fis = new FileInputStream(sorcefile);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
FileWriter fw=new FileWriter("src/output.java",true);
BufferedWriter bw=new BufferedWriter(fw);
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
bw.append(strLine);
}
//Close the input stream
br.close();
dis.close();
fis.close();
fw.flush();
bw.flush();
fw.close();
bw.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String args[])
{
FileReadWrite frw=new FileReadWrite();
frw.writeFile("sorce file name wit hfull path");
}
}

Categories

Resources