File cannot be deleted - java

Hi every one i'm programming a server client program which transfers file from client to server some files cannot be accepted and i should delete them after a test but the problem is file.delete() doesn't work for me cuz get an error that says file is open i java VM ;
package Serveur;
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
public class Serveur {
private static final int PORT =23456;
private ServerSocket serverSkt = null;
private Socket sock = null;
private FileOutputStream fos = null;
private boolean isStopped=false;
private InputStream fis;
private DataInputStream dis = null;
private int idUtil=0;
private String nomFichier = null;
private int taille = 0;
public Serveur() throws ClassNotFoundException, SQLException{
try {
serverSkt = new ServerSocket(PORT);
while(!isStopped){
sock=serverSkt.accept();
if(sock.isConnected()) {
fis=sock.getInputStream();
dis = new DataInputStream(fis);
idUtil=dis.readByte();
taille=dis.readInt();
nomFichier=dis.readUTF();
File fichier = new File("C:/Users/muddo/workspace/PFE/fichiers recu/"+nomFichier);
fos = new FileOutputStream(fichier);
byte[] bytes = new byte[taille];
int count=0;
while((count=dis.read(bytes)) > 0){
fos.write(bytes, 0, count);
}
dis.close();
fis.close();
fos.flush();
fos.close();
sock.close();
new max_allowed_packet();
String ext= fichier.getName().split("\\.")[1];
if(ext.equals("csv") || ext.equals("CSV") || ext.equals("Csv")){
TestCSV tc = new TestCSV(fichier.getAbsolutePath());
if(tc.test()==1){
new ChargerFichierCSV(fichier.getAbsolutePath());
}
else{
fichier.delete();
}
}
else {
new ChargerFichier(fichier.getAbsolutePath(),idUtil);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void arreterServeur() throws IOException{
if(dis != null)
dis.close();
if(fis != null)
fis.close();
if(fos != null)
fos.close();
if(!sock.isClosed())
sock.close();
if(!serverSkt.isClosed())
serverSkt.close();
isStopped=true;
}
}

The server could be running with another user than the user than owns the file. Did you check file permissions??
File fichier = new File("C:/Users/muddo/workspace/PFE/fichiers recu/"+nomFichier);
The file is owned by user muddo and the server may be running in another user with less privileges. This seems like a bad idea. You should put shared files in a shared folder. Or give permissions to the server user.

Related

java: Transfer a file to the server and get the file from the server in upper case

i want to send a .txt file from the client to server and get it back in upper case.
But this code do nothing.can anyone tell what is wrong here..?
SERVER : getting file from client and sending it back in upper case to the client.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
public class Assignment4_Server {
public static void main(String[] args) throws IOException {
byte[] bytearray = new byte[4096];
try (ServerSocket ss = new ServerSocket(4444)) {
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
int count;
String data = null ;
while((count = is.read(bytearray))>0){
data = Arrays.toString(bytearray).toUpperCase();
byte[] bytearrayout = data.getBytes();
os.write(bytearrayout);
}
s.close();
}
}
}
CLIENT : sending text.txt file to the server and getting file back after converted in upper case.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Assignment4_client {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
byte[] bytearray = new byte[4096];
Socket sc = new Socket("localhost",4444);
//send file
int countS , countR;
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = sc.getOutputStream();
while((countS = bis.read(bytearray))>0){
os.write(bytearray);
}
//recieve file in uppercase from server
InputStream is = sc.getInputStream();
byte[] bytearray2 = new byte[4096];
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while((countR = is.read(bytearray2))>0){
bos.write(bytearray2);
}
}
}
Here is a code that should help you. But before reading it you should be aware of what is happening:
Your client is not sending a 'stop reading' information to the server (read the client code below). That's why the server is stuck in the while loop when it is trying to read the data sent by the client. That is probably why you have tried to send the data back directly to the client. Shut down the socket output from the client side to respect the Socket contract and correctly free the socket (see TCP/IP).
The solution given doesn't take in account that the server should stay up after it has done its duty. Then, the server will not be able to serve more than one client at a time. This server is offering a one time service, which is pointless. To overcome this issue you should put everything in a while loop and bind every new server process into a new thread (I let you do that, its quite a joy).
The server doesn't take in account the whole size of the data an it could possibly run into an out of memory error if the data is too heavy. You should find a way to avoid this problem in a real implementation.
Both program should catch the exception and log it somewhere so you could be aware of any errors.
Writing a server is not so simple. You should normally write some kind of protocol with headers and other stuff like that. To avoid that, use objects like ObjectOutputStream and ObjectInputStream but it has some limitation like constraining your server in the Java world.
CLIENT
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Client {
public void send(File file)
{
Socket sc = null;
try
{
byte[] bytearray = new byte[4096];
sc = new Socket("localhost", 4444);
// 1. Read the file, send its content, close it.
int count;
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = sc.getOutputStream();
while((count = bis.read(bytearray))>0)
{
os.write(bytearray);
}
fis.close();
sc.shutdownOutput();
// 2. Delete old file, receive data, write it to new File.
InputStream is = sc.getInputStream();
bytearray = new byte[4096];
// Eventually do what you want with the file: new one, append, etc.
file.delete();
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
count = 0;
while((count = is.read(bytearray)) > 0)
{
bos.write(bytearray, 0, count);
}
fos.close();
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (sc != null)
{
try
{
sc.close();
} catch (IOException e) {}
}
}
}
}
SERVER
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
Server()
{
Socket s = null;
byte[] bytearray = new byte[4096];
try (ServerSocket ss = new ServerSocket(4444))
{
s = ss.accept();
InputStream is = s.getInputStream();
// 1. Recieve data and put it to UpperCase.
String data = "";
int count;
while((count = is.read(bytearray)) > 0)
{
data += new String(bytearray, 0, count);
}
data = data.toUpperCase();
System.out.println(data);
// 2. Send back data.
OutputStream os = s.getOutputStream();
os.write(data.getBytes());
os.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
TEST PROGRAM
This one should help you to test your both programs in the same project in an IDE.
import java.io.File;
public class Test
{
public static void main(String[] args)
{
Client c = new Client();
(new Thread()
{
public void run()
{
Server s = new Server();
}
}).start();
c.send(new File("test.txt"));
}
}
What is wrong here is two simple things.
The server is reading until end of stream, on a socket that must be used for the reply. The client therefore cannot close it after sending the request to provide the EOS, so it must shutdown the socket for output after sending the request.
Your copy loops are wrong. The general form is:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
You are ignoring the read count when writing, so you will write junk at end of stream, or any other time that read() doesn't fill buffer, which can be any time at all.

Can't accept connection to http server socket

I am trying to create a simple server, but am having a problem with trying to accept the connection, specifically the line "connectionSocket = serverSocket.accept();". I also have another class SimpleHttpHandler which handles the connection which is referenced in this code.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHttpServer {
private String rootDirectory;
private int port;
private ServerSocket serverSocket;
private Socket connectionSocket;
public SimpleHttpServer(String rootDirectory, int port) {
this.rootDirectory = rootDirectory;
this.port = port;
}
public void start() {
// Establish the listen socket
try {
serverSocket = new ServerSocket(port);
System.out.println("Server started");
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
System.out.println("Inside while");
// Listen for a TCP connection request
try {
connectionSocket = serverSocket.accept();
System.out.println("Client connected");
SimpleHttpHandler simpleHandler = new SimpleHttpHandler(rootDirectory);
simpleHandler.handle(connectionSocket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SimpleHttpServer server = new SimpleHttpServer(args[0], Integer.parseInt(args[1]));
server.start();
}
}
When I accept a new connection, I need to create a handler to handle it.
The Handler class is:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import org.omg.CORBA.Request;
public class SimpleHttpHandler {
private String rootDirectory;
private StringBuffer readFile;
private FileInputStream fileInputStream;
private File file;
private int b;
public SimpleHttpHandler(String rootDirectory) {
this.rootDirectory = rootDirectory;
}
public void handle(Socket remote) {
try {
// Create in and out streams
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
PrintStream out = new PrintStream(remote.getOutputStream());
// HTTP requests resolved here based on the protocol
// Read a string line from client
String line = in.readLine();
// Send a string to client
out.println("Not yet implemented");
// Send an empty line to client
out.println();
// Send a byte to client
out.write(123);
// Read a byte from file
file = this.requestFile(rootDirectory, line);
fileInputStream = new FileInputStream(file);
b = fileInputStream.read(); // it returns -1 at end of file
// Read the file
BufferedReader fileReader = new BufferedReader(new FileReader(file));
readFile = null;
while(fileReader.readLine() != null) {
readFile.append(fileReader);
}
if(!file.equals(null)) {
responseMessage(readFile.toString());
} else {
errorMessage();
}
// Close the remote socket and r/w objects
in.close();
out.close();
remote.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void errorMessage() {
System.out.println(readFile);
System.out.println("HTTP/1.0 500 Internal Server Error");
System.out.println();
System.out.println("^_^ Internal Server Error!");
;
}
private void responseMessage(String string) {
System.out.println("HTTP/1.0 200 OK");
System.out.println();
System.out.println("Hello World!");
}
public File requestFile(String rootDirectory, String path) {
// Construct a full path by connecting <rootDirectory> and requested relative path
File file = new File(rootDirectory, path);
// If it is a directory
// Then load the file index.html
if (file.isDirectory()) {
file = new File(file, "index.html");
}
// If the file exists, the file object is returned
// Otherwise null is returned
if (file.exists()) {
return file;
} else {
return null;
}
}
}

Java Socket - Sending files over sockets

I've been working on a Client/Server project and I'm stuck. I'm trying to write a back-up server so I can back-up my files to a remote computer. The problem is when I try to back-up my /home/user file, it gives me the following error on the server side:
java.io.UTFDataFormatException: malformed input around byte ...
I first send the size of the file, then I read the file into a byte array and then is send this byte array at once to the server, who receives it in a byte array it constructed using the file size. Is it a better solution to divide files into chunks or will the error remain?
This usually happens on a .zip file, but it doesn't always happen so that is why I'm confused. Can anyone help me out?
Code:
Server:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket server;
private Socket acceptingSocket;
public Server(int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Try again");
}
}
public void run(){
BufferedInputStream buffer = null;
DataInputStream reader = null;
int size = 0;
try {
acceptingSocket = server.accept();
buffer = new BufferedInputStream(acceptingSocket.getInputStream());
reader = new DataInputStream(buffer);
size = reader.readInt();
} catch (IOException e1) {
}
System.out.println("Size: " + size);
for(int j = 0; j < size; j++){
try {
String path = reader.readUTF();
System.out.println("Path: " + path);
long length = reader.readLong();
System.out.println("Length: "+length);
boolean dir = reader.readBoolean();
System.out.println("Dir? " + dir);
path = "/backup" + path;
File file = new File(path);
if(!dir){
int t = file.getAbsolutePath().lastIndexOf("/");
String dirs = file.getAbsolutePath().substring(0, t);
File direcs = new File(dirs);
System.out.println(direcs.mkdirs());
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[(int) length];
int bytes = reader.read(b, 0, (int)length);
if(bytes != -1)
bos.write(b,0,(int)length);
BufferedOutputStream out = new BufferedOutputStream(acceptingSocket.getOutputStream());
DataOutputStream writer = new DataOutputStream(out);
writer.writeUTF("File " + file.getAbsolutePath() + " is created!");
writer.flush();
bos.close();
} else file.mkdirs();
} catch (IOException e) {
System.out.println(e);
}
}
}
public static void main(String[] args){
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
while(true)
server.run();
}
}
Client:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Client {
private DataInputStream serverToClient;
private Socket client;
private DataOutputStream clientToServer;
private String name;
public Client(String name, int port){
try {
client = new Socket(name, port);
//receive response server
serverToClient = new DataInputStream(client.getInputStream());
//send message to server
clientToServer = new DataOutputStream(client.getOutputStream());
this.name = name;
}
catch (IOException e) {
}
}
public void backUp(String filePath){
File file = new File(filePath);
CopyOnWriteArrayList<File> files = new CopyOnWriteArrayList<File>();
if(file.exists()){
try{
if(file.isDirectory()){
ArrayList<File> f = setToList(file.listFiles());
files.addAll(f);
for(File sendF : files){
if(sendF.isDirectory()){
files.addAll(setToList(sendF.listFiles()));
if(!setToList(sendF.listFiles()).isEmpty()) files.remove(sendF);
}
}
} else{
files.add(file);
}
clientToServer.writeInt(files.size());
for(File fi : files){
boolean dir = false;
if(fi.isDirectory()) dir = true;
clientToServer.writeUTF(fi.getAbsolutePath());
System.out.println(fi.getAbsolutePath());
long length = fi.length();
clientToServer.writeLong(length);
clientToServer.writeBoolean(dir);
System.out.println(length);
if(!dir){
FileInputStream fis = new FileInputStream(fi);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)length];
bis.read(buffer, 0, (int)length);
clientToServer.write(buffer);
System.out.println(serverToClient.readUTF());
bis.close();
fis.close();
}
}
} catch(IOException e){
}
} else System.out.println("File doesn't exist");
}
private ArrayList<File> setToList(File[] listFiles) {
ArrayList<File> newFiles = new ArrayList<File>();
for(File lf : listFiles){
newFiles.add(lf);
}
return newFiles;
}
public static void main(String[] args){
String name = args[0];
int port = Integer.parseInt(args[1]);
System.out.println("Name: " + name + " Port: " + port);
Client client = new Client(name, port);
File file = new File(args[2]);
if(file.exists())client.backUp(args[2]);
else System.out.println("File doesn't exist");
}
}

FTP connection interruption Exception not thrown

I am trying to make a ftp downloader which would restart from the position where the file was lastly read.
I will be storing some meta-data for this . But while testing i am kicking out the client and also disconnecting the server . But the handle is not getting into the exceptional as indicated in the code:
package fileresumes;
/**
*
* #author agarwall
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
public class FileRes {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
int totalBytesRead = 0;
try {
client.connect("localhost");
client.login("anonymous", "");
// The remote filename to be downloaded.
String filename = "testing.txt";
fos = new FileOutputStream(filename);
boolean append = false;
int offset = 0;
long last_modified = 0;
int size = 0;
//long ro = client.getRestartOffset();
//ro = client.getRestartOffset();
//Download file from FTP server;
final File file = new File("C:/users/deadman/Desktop/", "testing.txt");
if (file.exists()) {
last_modified = file.lastModified(); // lastModified() returns the milliseconds since 1970-01-01
append = true;
// Read offset from meta-data file
size = (int) file.length();
offset = size;
}
//Setting the offset to resume download
client.setRestartOffset(offset);
InputStream inputFileStream;
inputFileStream = client.retrieveFileStream("/large.txt");
int bytesRead = 0;
try {
OutputStream out = new FileOutputStream(file, append);
final byte[] bytes = new byte[1024];
while ((bytesRead = inputFileStream.read(bytes)) != -1) {
out.write(bytes, 0, bytesRead);
totalBytesRead += bytesRead;
}
inputFileStream.close();
out.flush();
int get_reply_code = client.getReplyCode();
System.out.println(get_reply_code);
} catch (IOException e) {
// I want my metadata to be updated here .
System.out.println("IOException");
} catch (RuntimeException e) {
// I want my metadata to be updated here .
System.out.println("Runtime Exception ");
} finally {
try {
int get_reply_code = client.getReplyCode();
System.out.println(get_reply_code);
if (fos != null) {
fos.close();
}
client.disconnect();
System.out.println("finish");
} catch (IOException e) {
}
}
} catch (Exception e) {
}
}
}
Can anyone help me in case of broken connection how can we handle the exception here.
I have been trying to do something similar, and so far the only thing I have been able to do is to attempt another command. I haven't gotten to any transfers in coding yet, but for me if I login and there is either a timeout, get kicked, etc, if I try to change folders (or something similar) it throws a FTPConnectionClosedException. I have looked around Google, and have posted a question on here to see if there is a better way, but so far have not heard anything.

Object Input Stream only getting one file over network?

I have created a basic Client Server that will send image files in a specified directory over a network. The code worked last week but I came back to it today and it seems that I am only getting one file on the server side, even though the client prints out that it has sent all the image files in the directory.
It may be something in the client code but I think it is something on the server side.
Any help is greatly appreciated and if you have a more efficient solution, I am happy to change my code as necessary. My code is below:
ImageServer
package com.encima.network.server;
import java.io.*;
import java.net.*;
public class ImageServer{
ServerSocket ss;
Socket s;
ObjectOutputStream oos;
int port = 4440;
public ImageServer() throws IOException {
try {
ss = new ServerSocket(port);
System.out.println("Server started on Port: " + port);
} catch(IOException e) {
System.out.println("Serevr: Port-" + port + " not available, exiting.");
System.exit(0);
}
System.out.println("Server: Waiting for Client Connection...");
while(true) {
try {
s = ss.accept();
new ImageHandler(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
ImageServer is = new ImageServer();
}
}
ImageHandler
package com.encima.network.server;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ImageHandler implements Runnable {
Socket s;
int count = 0;
public ImageHandler(Socket socket) {
s = socket;
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("image" + System.nanoTime() + ".jpg");
count++;
//BufferedImage in = ImageIO.read(ois);
//ImageIO.write(in, "jpg", fos);
int ch = 0;
while(true) {
ch = ois.read();
if(ch == -1) {
break;
}
fos.write(ch);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Finally, the ImageClient
package com.encima.network.client;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
import com.encima.network.ImageFilter;
public class ImageClient {
Socket s;
String ip = "localhost";
int port = 4440;
ObjectOutputStream oos;
public ImageClient(File[] files) throws IOException, ClassNotFoundException, InterruptedException {
try {
s = new Socket(ip, port);
System.out.println("Client connected to Server via " + ip + " on port 80");
} catch (Exception e) {
System.out.println("Client: Cannot find Host: " + ip + ". Exiting.");
System.exit(0);
}
oos = new ObjectOutputStream(s.getOutputStream());
for(File f: files) {
sendFile(f);
}
oos.close();
//System.out.println("Written Image " + i + " of " + files.length);
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
File dir = new File("/Users/christophergwilliams/Dropbox/PhD/Projects/PhD/Year 1/GSN/images");
File[] files = dir.listFiles(new ImageFilter());
ImageClient ic = new ImageClient(files);
}
public void sendFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
//BufferedImage b = ImageIO.read(file);
//ImageIO.write(b, "jpg", oos);
int ch = 0;
while(true) {
ch = fis.read();
if(ch == -1) {
break;
}
oos.write(ch);
}
oos.flush();
System.out.println("Image Sent");
}
}
I am aware that it is a lot of code to read through but I do appreciate any help I can get on this!
I may be wrong but, for the sake of efficiency and network traffic, would it be beneficial to send the images as a zip from the client to the server?
Why are you using ObjectInputStream at all? You're not reading or writing any serialized objects - just raw binary data. Use whatever InputStream is provided, and read from that.
Anyway, that's not the big problem. The big problem is that you're just writing several files to one stream, with no indication of where one file is meant to finish and the next one is meant to start. How were you expecting to split the multiple files up? Options:
Use a delimiter between files (very ugly - you'd have to potentially escape any data which looked like the delimiter as you went along)
Prefix each file with its length
Send each file on a different connection
(You're also reading and writing a single byte at a time. Use the overloads of read/write which accept byte arrays.)

Categories

Resources