Why doesn't FileChannel append to end of file? - java

I am trying to download a few different files from a REST API using Java.
So far, I am getting the files, but the content won't append to the end of an output file.
I changed the FileOutputStream constructor from new FileOutputStream(path) to new FileOutputStream(path, true) but somehow it does not work.
Can somebody please provide pointers to what I am missing?
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class GetXML {
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
String filePath ="config/sample.txt";
Scanner in = new Scanner(System.in);
System.out.println("Enter the NO which you want to parse: ");
while(in.hasNextLine()){
String sampleUrl = "e.g.comSearch?NO=" + in.nextLine();
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath, true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
System.out.println("fOutStream closed");
}
if(rbcObj != null) {
rbcObj.close();
System.out.println("rbcObj closed");
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}
}
in.close();
System.out.println("Scanner Closed");
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
}
}

You have written:
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
The second parameter, 0, specifies that data should be transferred to the file at position zero. The position is absolute, and it doesn't matter that you opened the file for append, because you are ignoring the current channel position.
Note the documentation that states,
position - The position within the file at which the transfer is to begin; must be non-negative
Your code is an unconventional approach to a common task. As such, it's hard for readers to comprehend, and, when you encounter mistakes, hard for you to get help. Since URL only offers InputStream support, stick with streams, and avoid channels.

Related

download file process not ending when no internet connection for more than 10 minutes using java nio

Let me summarize my problem I am trying to download a file using java nio in that I have also written code for resuming the file download when you run the program again but my problem is this when there is no internet connection the download process is not stoping( what I meant is when there is no internet the code is not going to the next line no exception nothing it simply waits for the internet to resume .)
package com.jcg.java.nio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DownloadFileFromUrl {
// File Location
private static String filePath ="D:\\path\\app.zip";
// Sample Url Location
private static String sampleUrl = "server_url";
// private static int downloaded;
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
long downloaded=0l;
try {
long startTime = System.currentTimeMillis();
urlObj = new URL(sampleUrl);
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObj.openConnection();
File file=new File("D:\\path\\app.zip");
if(file.exists()){
System.out.println("if condition");
downloaded = file.length();
System.out.println(downloaded);
httpUrlConnection.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else{
httpUrlConnection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath,true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
long endTime = System.currentTimeMillis();
System.out.println(endTime);
System.out.println(endTime-startTime);
// System.out.println(System);
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
}
if(rbcObj != null) {
rbcObj.close();
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
// } else {
// System.out.println("File Not Present! Please Check!");
// }
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
// usingJavaNIO();
}
}
In the above code if you can see the below code of line
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
this is for downloading the file , when I disable the internet connection(no internet) than the control is not comming to the next line
System.out.println("! File Successfully Downloaded From The Url !");
and not in catch block either
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
And what I am trying to accomplish is that when there is no internet the process(download) or the channel should close and the rest of the code executes normally but what actually happens is until I reconnect my internet it will not stop(and after connecting internet still it takes time).
So in simple terms my application will even wait for hours to stop the download when there is no internet and there will be no errors.
Please someone help me to overcome this scenario I just want it to stop when there is no internet.

Deleting a line that starts with a particular number in a text file

I've been trying to come up with a class that deletes a line from a text file that starts with a particular number.
What I currently have doesn't show any code errors and also runs without erros; shows "BUILD SUCCESSFUL" on netbeans, but doesn't do anything to the line, or any part of the textfile whatsoever, let alone delete the intended line.
Could anyone please look at my code and please advise me on what I might have done wrong, or is missing?
Thanks a lot in advance.
Heres my code:
package Database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Edit {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File("/D:/TestFile.txt/");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(line.startsWith(lineToRemove))) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Edit edit = new Edit();
edit.removeLineFromFile("/D:/TestFile.txt/", "2013001");
}
}
There is a problem with your logic ... you are saying if the line equals to itself that starts with something which will never happen unless the line only consist of the line you want to remove
if (!line.trim().equals(line.startsWith(lineToRemove))
i think needs to be just
if (!line.startsWith(lineToRemove))
Change the if condition to:
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
}

Use a command line program from within Java

How can I use a command line program from within Java?
I'm trying to pass a graph definition in the dot-language (see Wikipedia) to the interpreter program dot (see GraphViz) through java.
The problem is, that the program does not answer, after I have sent the dot-graph to its InputStream, because it does not know, that I'm finished sending the description.
This is, what I currently have:
package exercise4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Main {
public static void main(String[] args) {
PrintStream out = System.out;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
final String start =
"strict graph LSR%1$d {\n" +
" node [shape=circle color=lightblue style=filled];\n\n" +
" {rank=same; A--B [label=6];}\n" +
" {rank=same; C--D [label=12]; D--E [label=4];}\n" +
" A--C [label=4]; B--D [label=4]; B--E [label=9];\n\n" +
" node [shape=record color=\"#000000FF\" fillcolor=\"#00000000\"];\n}\n";
Process dot = Runtime.getRuntime().exec("dot -Tsvg");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(dot.getOutputStream(), false, "UTF-8");
out.printf(start, 0);
out.flush();
out.close();
while(in.ready()) {
System.out.println(in.readLine());
}
in.close();
dot.destroy();
} catch (UnsupportedEncodingException ex) {
} catch (IOException ex) {
} finally {
out.close();
}
}
}
Looks as if you are reading from the wrong input stream. Have a look at this answer: https://stackoverflow.com/a/4741987/1686330

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Java How do I read and write an internal properties file?

I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");

Categories