I tried to upload a file to my jersey server, but there is an error.
Writer output = null;
File file = null;
try {
String text = "Rajesh Kumar";
file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = null;
try {
is = new FileInputStream(file);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FormDataMultiPart part = new FormDataMultiPart().field("file", is, MediaType.TEXT_PLAIN_TYPE);
System.out.println(is);
System.out.println(tenant1.getTenantId());
System.out.println(part);
String response = service.path("rest").path("file").type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
The Syso are not null. So the File was written to the inputstream.
Error:
ClientHandlerException: java.io.IOException: ReadError , when I send it to the server.
Server Side:
#POST
#Path("/file")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postFileTenant(#FormDataParam("file") InputStream stream) throws IOException {
// save it
return Response.ok(IOUtils.toString(stream)).build();
}
You are passing an InputStream that is closed so obviously Jersey runtime can't read from it. Remove is.close(); line from your code.
Related
Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public class helloWorldClient {
public static void main(String[] args) {
helloWorldClient crunchifyClient = new helloWorldClient();
crunchifyClient.getResponse();
}
private void getResponse() {
try {
Client client = Client.create();
WebResource webResource2 = client.resource("http://localhost:8080/Downloader/webapi/folder/zipFile");
ClientResponse response2 = webResource2.accept("application/zip").get(ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
}
String output2 = response2.getEntity(String.class);
System.out.println("\n============RESPONSE============");
System.out.println(output2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This program returning an unreadable output. but when I hit that URL "http://localhost:8080/Downloader/webapi/folder/zipFile" in browser "server.zip" file is getting downloaded.
My question is how can I read that response and write to some folder through java client program?
You can get the InputStream instead of String. Then just do your basic IO.
InputStream output2 = response2.getEntity(InputStream.class);
FileOutputStream out = new FileOutputStream(file);
// do io writing
// close streams
InputStream output2 = response2.getEntity(InputStream.class);
OutputStream out = new FileOutputStream(new File("/home/mpasala/Downloads/demo.zip"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = output2.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
output2.close();
out.close();
System.out.println("Done!");
Thanks to https://stackoverflow.com/users/2587435/peeskillet .
I want to make an android app that is actually a RSS reader. This will load XML file from a particular link like http://kalaerkantho.com/rss.xml. After downloading I know how to parse it. But my question is how to download it first so that I can process the downloaded file.
Try this:
private static void downloadFile(String url, String filePath) {
try {
File outputFile = new File(filePath);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
Adapted from this answer.
I try to create an asynctask that runs permanently (all the time my app is running). Thay task read every second a file on a server (status.xml).
My problem is that when I execute the app, I have an java.io.IOException: closed exception the second time I do :
reader.read(buffer); // HERE I HAVE AN IOException closed
(first loop is ok, then I have error each loop)
Thanks if someone can help me. I undesrtand the reason of the error, but I cannot find a solution...
Here is my code :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
URL url = new URL(address + "/status.xml");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer); // HERE I HAVE AN IOException closed
return new String(buffer);
}
}
Thank you.
Sorry for my question, I found my error, a stupid error.
Of course I need to openConnection for each GET.
I give the corrected code if it can help someone :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
URL url;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
url = new URL(address + "/file.xml");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
I'm trying to write some data into DataOutputStream from FileConnection.
FileConnection con = (FileConnection)Connector.open("file:///C:/file.txt");
if (!con.exists())
con.create();
DataOutputStream out = con.openDataOutputStream();
out.writeUTF("some text");
out.close();
con.close();
But rather than the text I've typed, I receive some garbage in the file - like there are some problems with encoding.
Ok, from what I can see it adds null and 0xFF sign at the start of a file.
What can be the cause?
Please Look at my method for writing Files in Java ME
I think you are missing Connector.READ_WRITE in your code,
private void writeTextFile(String fileName, String text)
{
DataOutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fileName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}