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());
}
}
}
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 create a method that will load a txt file and then change it but thats another method.
private void openFile() {
fileChooser.getSelectedFile();
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
}
What must go next in order to get data from the file after choosing it to manipulate its data?
The JFileChooser documentation has an example on how to continue your code, and get the name of the file chosen, which can then be turned into a File object. You should be able to modify that example to meet your needs:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Here's an example that might help you. I would want to read up on and try some simple examples on different buffers that will read and write. In fact, i have worked with these a lot in the last few months and I still have to go and look.
public class ReadWriteTextFile {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
static public void setContents(File aFile,
String aContents)
throws FileNotFoundException,
IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
output.write( aContents );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not
//certain but you can trap the error with a
//TRY-CATCH Block.
System.out.println("Original file contents: " + getContents(testFile));
setContents(testFile, "The content of this file has been overwritten...");
System.out.println("New file contents: " + getContents(testFile));
}
}
I have a method which loads file from sdcard (Android) and then reads it with StringBuilder. The text which im reading is written with my native language characters such as ą ś ć ź ż...
StringBuilder (or FileInputStream) can't read them properly unfortunately. How I can set proper encoding ?
here is the code :
File file = new File(filePath);
FileInputStream fis = null;
StringBuilder builder = new StringBuilder();
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
builder.append((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("File Contents = " + builder.toString());
contactService.updateContacts(builder.toString());
for example you could try an InputStreamReader combinded with a BufferedReader, that should do the trick:
InputStreamReader inputStreamReader = new InputStreamReader((InputStream)fis, "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
So long,
Tom
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.