New Created File Can't Open in Java - java

My else if block will verify the result from remote service.
If the result matches, it will trigger another API call to contact the remote service again. The remote service will send back a file to my client program.
I tested all my code and it is working but I am not able to open back the new file and it's showing the file was corrupted. My client program will read the file from the remote service and write it into another file name in a different directory.
This is my source code:
else if (result == 1 && value.equals("problem"))
{
String Url = "http://server_name:port/anything/anything/";
String DURL = Url.concat(iD);
System.out.println("URL is : " + DURL); // the remote API URL
URL theUrl = new URL (DURL);
HttpURLConnection con1 = (HttpURLConnection) theUrl.openConnection(); //API call
con1.setRequestMethod("GET");
con1.connect();
int responseCode = con1.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
ps.print(data1);
ps.close();
}
System.out.println("The new sanitized file is ready");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is my filePath mentioned in the code D:/file/red_new.docx. This is how I get my file path: String filePath = "D:/file/"+fn+"_new."+fileType;. The fn variable is the filename from the JSON string from the first API call while the fileType is the file type from the JSON string from the second API call. I add in the _new to indicate it's a new file and using java concatenate with the fn and fileType to obtain the full path.

You're creating a new output file per line of input, so you'll only ever get the last line. And you're also losing the line terminators. Try this:
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
while ((data1 = read1.readLine()) != null)
{
ps.println(data1);
}
ps.close();
You're also not closing the input stream.
If these files aren't all known to be text files you should be using InputStream and OutputStream.

Please use finally block to close the open streams. If stream is not closed, you can't open it until the process holding the stream is closed or released.
eg:
try( InputStream is1 = con1.getInputStream()){
// ...
}

Related

Error while Rename file in ftp folder Java

Following is my code to read the file and rename it afterwards. Im using apache commons.net 3.0.1.
client.connect(localhost);
boolean login = client.login("username", "password");
if(login){
System.out.println("login successful");
boolean chdir = client.changeWorkingDirectory("/home/folder1/child/");
String url = client.printWorkingDirectory(); // EDIT
FTPFile[] result = client.listFiles(url, filter);
if (result != null && result.length > 0) {
for (FTPFile aFile : result) {
try{
String filename = aFile.getName();
InputStream is= client.retrieveFileStream(filename);
br = new BufferedReader(new InputStreamReader(is));
while((line = br.readLine()) != null){
System.out.println("the line is"+line);
}
}
finally{
if(br!=null){
try{
br.close();
String oldFilename =url + "/" +aFile.getName();
String newFilename = "PRO"+aFile.getName();
boolean rename = client.rename(oldFilename, newFilename);
if(rename){
System.out.println("renamed");
}
else{
System.out.println("Error in renaming");
}
}
The file deosn't get renamed and the program prints
error in renaming files (cz boolean rename = false).
I have refereed to different examples. But all seems to show the same problem.
The file is picked after filter and read without any issues.
If anyone could point to what I'm doing wrong here, that'd be very helpful.
Here, the url is String url = client.printWorkingDirectory();
I have tried with both relative path and absolute path. And giving full path only to the oldFilename and just the filname to the newFilename. Both did not work.
EDIT
Before changing the directory, the url will be / which is root.
After changing the directory, the url will be /home/folder1/child/. This is the where the files exists.
InputStream retrieveFileStream(String remote):This method returns an InputStream which we can use to read bytes from the remote file. This method gives us more control on how to read and write the data. But there are two important points when using this method:
The method completePendingCommand() must be called afterward to finalize file transfer and check its return value to verify if the download is actually done successfully.
boolean success = ftpclient.completePendingCommand();
if (success){
System.out.println("File #2 has been downloaded successfully.");
}
We must close the InputStream explicitly.
is.close(); //is = InputStream
SOURCE

while downloading a file using java code, the lines in file skips the newline character

i am writing to a file using java code like this.
File errorfile = new File("ErrorFile.txt");
FileWriter ef = new FileWriter(errorfile, true);
BufferedWriter eb = new BufferedWriter(ef);
eb.write("the line contains error");
eb.newLine();
eb.write("the error being displayed");
eb.newLine();
eb.write("file ends");
eb.close();
ef.close();
this file is being saved on the server. now when i download the file using java code it skips the newline character. the code for downloading is:
String fname = "ErrorFile.txt";
BufferedInputStream filein = null;
BufferedOutputStream output = null;
try {
File file = new File(fname); // path of file
if (file.exists()) {
byte b[] = new byte[2048];
int len = 0;
filein = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/force-download");
response.setHeader("content-Disposition", "attachment; filename=" + fname); // downloaded file name
response.setHeader("content-Transfer-Encoding", "binary");
while ((len = filein.read(b)) > 0) {
output.write(b, 0, len);
output.flush();
}
output.close();
filein.close();
}
} catch (Exception e1) {
System.out.println("e2: " + e1.toString());
}
now when i open the downloaded file, it should look like:
the line contains error
the error being displayed
file ends
but the output is
the line contains error (then a box like structure) the error being displayed (then a box like structure) file ends.
please suggest...
#BalusC thats correct ... my server is linux and client is windows.. is theris any solution to this??
Any starting developer or at least computer enthusiast should know that Linux/Unix based operating systems use \n as newline character and that Windows uses \r\n as newline characters. The \n fails in Windows, however the \r\n works fine in Linux/Unix (it must, otherwise e.g. HTTP which also mandates \r\n would fail in Linux/Unix as well).
The newLine() method which you're using to print the newline only prints the system's default newline which is thus \n at your server. However, your client, which is Windows based, expects \r\n.
You need to replace
eb.newLine();
by
eb.write("\r\n");
in order to get it to work across platforms.
i used this code for my problem... and its working...
String fname = "ErrorFile.txt";
BufferedInputStream filein = null;
BufferedOutputStream output = null;
try {
File file = new File(fname); // path of file
if (file.exists()) {
int len = 0;
filein = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("content-Disposition", "attachment; filename=" + fname); // downloaded file name
while ((len = filein.read()) != -1) {
output.write(len);
output.flush();
}
output.close();
filein.close();
}
} catch (Exception e1) {
System.out.println("e2: " + e1.toString());
}

Main.class.getResource() and jTextArea

When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)

File Upload System not working quite right... can someone look at this code?

I created some code to handle basic file upload from a java client to a php server, but I'm having some issues with the naming and directory creation. Here is the important parts of the code:
The method I use to upload the file:
public static void uploadWithInfo(Uri uri, String title, String artist, String description) {
try {
String path = uri.getPath();
File file = new File(path);
URL url = new URL("http://**********/upload.php?title="+title+"&artist="+artist+"&description="+description);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int totalbytes = bis.available();
for(int i = 0; i < totalbytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It's just supposed to upload an audio file. The user inputs the artist, title, and a very short description if necessary. The actual file is uploaded just fine so I don't think any more java is necessary. Here is the code on the php end:
<?php
$uploadBase = "music/";
$uploadFolder = $_GET['artist']+"/";
$uploadFileName = $_GET['title'];
$uploadFileDescription = $_GET['description'];
$uploadPath = $uploadBase.$uploadFolder.$uploadFileName."%%D%%=".$uploadFileDescription.".mp3";
if(!is_dir($uploadBase)) {
mkdir($uploadBase);
}
if(!is_dir($uploadFolder)) {
mkdir($uploadFolder);
}
$incomingData = file_get_contents('php://input');
if(!$incomingData) {
die("No data.");
}
$fh = fopen($uploadPath, 'w') or die("Error opening path.");
fwrite($fh, $incomingData) or die("Error writing file.");
fclose($fh) or die("Error closing shop.");
echo "Success!";
?>
So I get all of the inputted values for title, artist, and description. Then I create 2 directories if they don't already exist: one for music and one for the artist the uploader input. Then I create a path of base(music)/folder(artist)/filename(title)"code to let me parse description"(%%D%%).mp3.
So a song Billie Jean by Michael Jackson with a description "favorite" should have a path of
music/Michael Jackson/Billie%20Jean%%D%%favorite.mp3
What I get however, is:
music/0Billie%%D%%=
The directory for artist is not created, there is a weird 0 before the title (which only includes the first word), and the description doesn't show.
I don't really know where I went wrong, can anyone give me some insight? Thank you.
Your InputStream.available() method does not do what you expect it to. Use the File size instead.
Edit:Use a multi-part upload instead. The Apache HttpClient supports it, google for examples.
Turns out it was a stupid error with some related php code. Sorry to trouble you all.

read file in an applet

Hi there I want to read out a file that lies on the server.
I get the path to the file by a parameter
<PARAM name=fileToRead value="http://someserver.de/file.txt">
when I now start the applet following error occurs
Caused by: java.lang.IllegalArgumentException: URI scheme is not "file"
Can someone give me a hint?
BufferedReader file;
String strFile = new String(getParameter("fileToRead"));
URL url = new URL(strFile);
URI uri = url.toURI();
try {
File theFile = new File(uri);
file = new BufferedReader(new FileReader(new File(uri)));
String input = "";
while ((input = file.readLine()) != null) {
words.add(input);
}
} catch (IOException ex) {
Logger.getLogger(Hedgeman.class.getName()).log(Level.SEVERE, null, ex);
}
File theFile = new File(uri);
is not the correct method. You accessing an URL, not a File.
Your code should look like this:
try
{
URL url = new URL(strFile);
InputStream in = url.openStream();
(... read file...)
in.close();
} catch(IOException err)
{
(... process error...)
}
You are trying open as a file, something which doesn't follow the file:// uri, as the error suggests.
If you want to use a URL, I suggest you just use url.openStream() which should be simpler.
You will need to sign the applet unless the file is being accessed from the same server/port that the applet came from.

Categories

Resources