ftpClient wont upload,what am I missing? - java

Yeah, so I am using this code but whenever I run it, it doesnt upload anything. I have a similar code in another program the works perfect. What have I missed?
public void upload(){
new Thread(new Runnable() {
public void run() {
if (Looper.myLooper() == null)
{
Looper.prepare();
}
FTPClient ftpClient = new FTPClient();
FileInputStream inputStream = null;
int Upload = sharedPreferences.getInt("Upload", 1);
if (Upload == 1) {
try {
ftpClient.connect(InetAddress.getByName("XXX.net"));
ftpClient.login("XXX", "XXX");
ftpClient.changeWorkingDirectory("/public_html/Images/Cross");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
File file = new File(getApplicationInfo().dataDir + "/files/" + "temp" + ".jpg");
inputStream = new FileInputStream(file);
ftpClient.storeFile("temporary.jpg", inputStream);
file.delete();
ftpClient.logout();
ftpClient.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
...
}

Related

ObjectInputStream isn't finding any data to pull?

I am trying to read and write shape objects to a file for a drawing program, but when I try to read from the file it shows that the file is empty. The file is definitely being written to and updated, but when trying to read from the file it is showing that there are zero bytes available. The shape class is serializable so I am not sure why this isn't working at all.
public void writeToFile() {
try {
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (Shape item : shapes) {
out.writeObject(item);
}
out.close();
fileOut.close();
System.out.println("Serialized data is saved in output.ser");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadFromFile() {
boolean cont = true;
Shape shape = null;
int count = 0;
while (cont) {
try {
FileInputStream fileIn = new FileInputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
if (in.available() != 0) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
} else {
cont = false;
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Alright for some reason the .available() method isn't showing any bytes regardless of if there actually are any or not. To counter this I just threw in another try/catch statement where it continuously reads objects until it hits an EOFException and catches itself.
My code ended up looking like this once working.
public void loadFromFile() {
//** Loads set of shape objects from file
Shape shape = null;
int count = 0;
try {
FileInputStream fileIn = new FileInputStream("save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
try {
while (true) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
}
} catch (EOFException e) {
System.out.println("End of file exception");
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
repaint();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Delete a directory after untar a file

I have a .tar.gz file and I want to untar that same file.
To do that I have this function in java:
private void unTarFile(String tarFile, File destFile) {
TarArchiveInputStream tis = null;
FileInputStream fis = null;
GZIPInputStream gzipInputStream = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(tarFile);
bis = new BufferedInputStream(fis);
// .gz
gzipInputStream = new GZIPInputStream(bis);
// .tar.gz
tis = new TarArchiveInputStream(gzipInputStream);
TarArchiveEntry tarEntry = null;
while ((tarEntry = tis.getNextTarEntry()) != null) {
System.out.println(" tar entry- " + tarEntry.getName());
if (tarEntry.isDirectory()) {
continue;
} else {
// In case entry is for file ensure parent directory is in place
// and write file content to Output Stream
File outputFile = new File(destFile + File.separator + tarEntry.getName());
outputFile.getParentFile().mkdirs();
IOUtils.copy(tis, new FileOutputStream(outputFile));
}
}
} catch (IOException ex) {
System.out.println("Error while untarring a file- " + ex.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (gzipInputStream != null) {
try {
gzipInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (tis != null) {
try {
tis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This works and I can untar my .tar.gz successfully.
I can edit the files of the untarred directory to, but when I try to delete my directory I cant:
Did I forgot to close something?

Java app can't be closed even "CLOSE ON EXIT", TCP Server

I just wanna make a Server application which gets Strings and put these into a JTextArea. There are two errors I get, even no errors are showed.
the window can't be closed although I used this statement:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If the client connects to the Server, the whole window turns black. What could be the error? Here the code:
Client:
public Main() {
super("Main");
setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/ic.png")));
panelFields = new JPanel();
panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));
panelFields2 = new JPanel();
panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));
scrollPane = new JScrollPane();
panelFields.add(scrollPane);
getContentPane().add(panelFields);
getContentPane().add(panelFields2);
getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
setSize(326, 264);
setVisible(true);
messagesArea = new JTextArea();
scrollPane.setViewportView(messagesArea);
messagesArea.setColumns(30);
messagesArea.setRows(10);
messagesArea.setEditable(false);
startServer = new JButton("Start");
startServer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
socketConnection();
startServer.setEnabled(false);
}
});
panelFields.add(startServer);
}
And the Server connection:
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Maybe you could tell me, how I can fix those problems and also, how I can make, that the server doesn't close the socket although the client disconnects. I wanna reconnect maybe later...
You need to start your socket listener in its own thread, and you need to add a window close listener that shuts down that thread.
For example:
private ServerSocket serverSocket = null;
private boolean done = false;
private void startServer() {
Thread t = new Thread(new Runnable() {
public void Run() {
socketConnection();
});
}
t.start();
}
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
while (!done) {
try {
final Socket socket = serverSocket.accept();
Thread t = new Thread(new Runnable() {
public void Run() {
handle(socket);
}
});
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handle(Socket socket) {
if (socket == null) return;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e) {
done = true;
socketServer.close();
}
Your button click listener should call startServer(), then your window close function would set done = true and call socketServer.close().
Now you have one thread for the UI, one thread for the socket server, and one thread for each connection to the server.

AudioRecord not saving

I am trying to record the audio using AudioRecorde.
Though it creates file but could not record it. Please provide some inputs.
private void startRecording(){
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,44100,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
try {
recorder.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
At the time of stoprecording
private void stopRecording(){
if(null != recorder){
recorder.stop();
recorder.release();
FileOutputStream fOut = null;
try{
int buffSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
//ByteBuffer buffer = ByteBuffer.allocate(AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
byte b[] = new byte[buffSize];
recorder.read(b,0,buffSize);
//getFilename() will get the file
fOut = new FileOutputStream(getFilename());
fOut.write(b);
}catch(Exception e){
e.printStackTrace();
}finally{
if(fOut != null){
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
recorder = null;
}
}
It creates a file with buffsize but could not play it.
Here is the code for playing the file
private void startPlaying() {
mPlayer = new MediaPlayer();
if(playing){
playing = false;
}else{
try {
File myFile = new File(prevFile);
txtStatus.setText("Playing...");
imgStatus.setVisibility(View.VISIBLE);
imgStatus.setBackgroundDrawable(getResources().getDrawable(R.drawable.play_small));
if(myFile.exists()){
System.out.println("file is exist");
}else{
System.out.println("file is not exist");
}
mPlayer.setDataSource(prevFile);
System.out.println("file path is is ::> " + prevFile);
mPlayer.prepare();
mPlayer.start();
playing = true;
} catch (IOException e) {
e.printStackTrace();
write.saveToFile(getApplicationContext(), "prepare() failed"+"\n");
}
}
}

Java Client Server "Socket is closed"

I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !

Categories