I'm writing a java server and always read requests form the browser. For example, I have in browser http://localhost:8080/C:\Users\1\Desktop\tur.txt and read this request. Then saves a file path. Then I want to print the contents of the file to browser. For example, some text which is in tur.txt.
I'm doing it with a method in another class.
Here is a code of this class:
public class FileReader {
BufferedReader in;
File DataFile;
public void Reader(String directory, PrintStream out) throws IOException {
try {
File stockInputFile = new File(directory);
File StockOutputFile = new File(directory);
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count;
if (new File(directory).isDirectory()) {
directory=directory.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n"+
"Location: /"+directory+"/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f=new FileInputStream(directory);
// Determine the MIME type and print HTTP header
String mimeType="text/plain";
if (directory.endsWith(".html") || directory.endsWith(".htm"))
mimeType="text/html";
else if (directory.endsWith(".jpg") || directory.endsWith(".jpeg"))
mimeType="image/jpeg";
else if (directory.endsWith(".gif"))
mimeType="image/gif";
else if (directory.endsWith(".txt"))
mimeType="text/txt";
else if (directory.endsWith(".class"))
mimeType="application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n"+
"Content-type: "+mimeType+"\r\n\r\n");
System.out.println(mimeType);
// Send file contents to client, then close the connection
byte[] a=new byte[4096];
int n;
while ((n=f.read(a))>0)
out.write(a, 0, n);
// out.flush();
out.close();
}
catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n"+
"Content-type: text/html\r\n\r\n"+
"<html><head></head><body>"+directory+" not found</body></html>\n");
out.close();
}
}
}
It takes a directory to find a file a file on disk and PrintStream (PrintStream out = new PrintStream(new BufferedOutputStream(serSock.getOutputStream()));) to print the content to browser. But, the problem is that when I read this file. The content of this file removes. That means all that text that I had in tur.txt deletes. And the file becomes emtpty intead of beeng printed to the browser.
Can anyone explain why? Thank you.
The problem was here:
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
In FileOutputSteam. So when I deleted these 2 lines the program started to work correctly. I forgot that FileOutputStream clears all the data stored in the file.
I would like to thank #lamsomeone for his help.
Related
I am currently working a project and we have divided it in modules, in one of them, we have a file ( .exe ) extension. I decided to open it in binary format and read the contents of it, modify them. But, I am not to modify the changes and save it in the same file. When I am trying to do so, it says 0KB. It's working perfectly fine when using two files.
Here is the source code :
public static void main(String[] args) {
String strSourceFile="E:/e.exe";
String strDestinationFile="E:/f.exe";
try
{
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while( (noOfBytes = fin.read(b)) != -1 )
{
fout.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin.close();
fout.close();
Use RandomAccessFile or You can also create a new file with your changes save it and delete the original one. Once original file is deleted then rename this new file to the original one.
You are trying to read and write the same file with the input and the output stream so the file is not getting copied while you try to do it with the same file. Instead, use a middle file as the buffer, as in the below code I have used the f.exe as the middle buffer, next I have copied the data from the buffer file again to the original file jar.exe, at last you need to delete the buffer file.
Here is the below code :
String strSourceFile = "C:/jar.exe";
String strDestinationFile = "C:/f.exe";
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while ((noOfBytes = fin.read(b)) != -1) {
fout.write(b, 0, noOfBytes);
}
fin.close();
fout.close();
String strDestinationFile1 = "C:/jar.exe";
FileInputStream fin1 = new FileInputStream(strDestinationFile);
FileOutputStream fout1 = new FileOutputStream(strDestinationFile1);
while ((noOfBytes = fin1.read(b)) != -1) {
fout1.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin1.close();
fout1.close();
File file = new File("C:/f.exe");
file.delete();
I am doing a program which will receiving any file from my remote server, these files can be .doc, .pdf and some others file type. I will read the content in those files and write it into another new files with same file extension. But when i receive a .doc file from remote server and i try read the file and write into another file, it's show me something like this #²Ó\ç¨ Þ¢·S \Ò Þ¢·S \Ò PK £ JT in my test.doc. i have no idea on this issues, i try PrintStream,BufferedWriter or PrintWriter but unfortunately it's wouldn't help anything This is my source code for read/write the file
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintWriter pw = new PrintWriter("test.doc","UTF-8");
pw.write(data1);
pw.close();
}
System.out.println("done");
}
catch(IOException e)
{
e.printStackTrace();
}
May i know what is the best way to do the read/write if we having difference file type ?
These file types have binary data and should not be read as characters. (Also, note that you are creating a new PrintWriter every time through the while loop. This will never work.) Just deal with the binary data directly. Something like this (untested) might work:
InputStream is1 = con1.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is1);
byte[] buffer = new byte[2048]; // or whatever size you want
int n;
OutputStream os = new FileOutputStream("test.doc");
while ((n = bis.read(buffer)) >= 0) {
os.write(buffer, 0, n);
}
os.close();
bis.close();
Also, you should be using a try with resources statement.
Other approach (more concise, more expressive):
Files.copy(is1, Paths.get("test.doc"), StandardCopyOption.REPLACE_EXISTING);
I have a .xlsx file (or any file) which I would like to gzip. I am able to gzip the file but now I have the problem of trying to do this in place. Meaning to replace the original file with the gzipped version of the file.
Here is my code:
public static void main(String[] args) throws IOException {
File file = new File("test.xlsx");
File gfile = new File(file.getAbsolutePath()+".gz");
if(!file.exists()) {
System.err.println("Input tax file did not exist!");
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(gfile);
GZIPOutputStream gos = new GZIPOutputStream(fos);
gzipReplace(fis, gos);
}
private static void gzipReplace(InputStream is, OutputStream os) {
int oneByte;
try {
while( (oneByte = is.read()) != -1 ) {
os.write(oneByte);
}
os.close();
is.close();
} catch (Exception e){
System.err.println(e.getStackTrace());
}
}
How can I do an in-place replacement of an uncompressed file with a gzipped one?
Just use File.delete() on the original file after successful compression and writing of the gzip file.
You must be very careful to not delete the original file until you are certain that the new compressed file was successfully written and closed. Otherwise you are setting yourself up to lose data.
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());
}
I'm currently writing a function what would create a zip file, which will be used in other functionality. Below it is my function's code:
public void createZip(){
try{
String outfile = this.filename + ".zip";
//input file
FileInputStream input = new FileInputStream(this.filename);
//output file
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(outfile));
//name the file inside the zip file
System.out.println(this.filename);
zip.putNextEntry(new ZipEntry(this.filename));
byte[] buffer = new byte[this.BUFFER];
int len;
//copy the file to the zip
while((len= input.read(buffer)) > 0){
System.out.println(len);
zip.write(buffer, 0, len);
}
zip.closeEntry();
zip.flush();
input.close();
zip.close();
this.filename += ".zip";
}
catch(IOException e){
e.printStackTrace();
}
}
I have tried to debug, but I couldn't find the source of this problem. The function runs without any further problems, but the zip file produced it is an empty one.
You must close the entry using ZipOutputStream#closeEntry() prior to closing the output stream, or the entry is never confirmed to have been written entirely.
Also, the name of the ZipEntry cannot be the entire path; i.e, it should be dog.png instead of C:\Users\Admin\Documents\dog.png. This issue will pass by without an exception, and will cause the data from the file to be compressed directly into the zip, rather than into the zip as a compressed file.
final static byte[] EmptyZip={80,75,05,06,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00};
public static void createEmptyZip(String path){
try{
FileOutputStream fos=new FileOutputStream(new File(path));
fos.write(EmptyZip, 0, 22);
fos.flush();
fos.close();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
well, just wondering why you pass a filename as a parameter if you dont use it within the code..
Since you are always using the this.filename. That makes me think that you are trying to name a zip file with a name you set into the objects state and since you are also using that same name in the ZipEntry its trying to add that same zipper file inside it.. since the ZipEntry must point to an existing file, thats why it comes up empty.
Hope it helps.
Try to flush the buffer by using zip.flush() before closing, although close should flush the buffer.
Also verify this.filename. You have a local variable with the same name. The local variable filename is never used. It's possible the zip file is being written to a different location than what you expect.
#phillipe try this please
public void createZip(String filename) {
try {
//input file
FileInputStream input = new FileInputStream(filename);
//output file
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(filename + ".zip"));
//name the file inside the zip file
zip.putNextEntry(new ZipEntry(filename));
byte[] buffer = new byte[1024];
int len;
//copy the file to the zip
while((len = input.read(buffer)) > 0) {
System.out.println();
zip.write(buffer, 0 , len);
}
zip.closeEntry();
zip.flush();
zip.close();
input.close();
filename += ".zip";
} catch(IOException e) {
e.printStackTrace();
}
}
those code create a zip file and that's work and for me too. :)
Simple solution. Make one manual directory in ZipEntry without File Separator.
zip.putNextEntry(new ZipEntry("LOG" + fileName));
instead of
zip.putNextEntry(new ZipEntry(fileName));
Here fileName = file.getAbsoluteFile();
This will first create LOG dir in zip file followed by fileNames with directory path. This avoids creating initial empty directory in zip file.