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
Related
so I want to store the file I read into an array but I am not sure how to. I am trying to use an arraylist but when I compile it in the console I don't it is not the same as the text file
this is my code
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
String line = null;
ArrayList<String> list = new ArrayList<String>();
try {
fr = new FileReader("sample.txt");
br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
list.add(line);
line = br.readLine();
for(String s : list){
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
it looks to me like you're double advancing your position in the file by having line=br.readLine() both in your while condition and after adding to the ArrayList. Also, is there a reason that you're outputting the contents before you've processed the entire file instead of outside the while loop?
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'm trying to implement SHA-1 on Android with the following code
String name = "potato";
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getBytes("iso-8859-1"), 0 , name.getBytes( "iso-8859-1").length );
Bytes[] sha1hash = md.digest();
textview.setText(sha1hash.toString());
but when i run this code twice, it gives me different hash codes to "potato". As far as i know they should give me the same answer every time i run the program, anyone have any idea what problem could it be?
You can use this Code for getting SHA-1 value.
public class sha1Calculate {
public static void main(String[] args)throws Exception
{
File file = new File("D:\\Android Links.txt");
String outputTxt= "";
String hashcode = null;
try {
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = data;
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for( byte b : bytes )
{
sb.append( String.format("%02X", b) );
}
System.out.println("Digest(in hex format):: " + sb.toString());
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try this Link for any Help.
http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/
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.
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());
}
}
}