Displaying character when read into file - encoding - java

I have a problem with the encoding of text when I display it into my text area.
The problem is when there are character like : é à è
I have in my text area ? ? ? instead
Here is the part of code to read my file :
private void importerActionPerformed(java.awt.event.ActionEvent evt) {
jTabbedPane1.setSelectedIndex(0);
try {
JFileChooser explorer = new JFileChooser(chemin);
int answer = explorer.showOpenDialog(this);
if (answer == JFileChooser.APPROVE_OPTION) {
chemin = explorer.getCurrentDirectory().getAbsolutePath();
String name = explorer.getSelectedFile().getCanonicalPath();
System.out.println("name : "+name);
texte.setText("");
File file = new File(name);
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String result = in.readUTF();
texte.setText(result);
in.close();
System.out.println("Erreur la");
} catch (IOException e) {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String result = null;
result = "";
byte[] buff = new byte[2048];
int read = in.read(buff, 0, 2048);
while (read >= 0) {
String substr = new String(buff, 0, read);
result += substr;
read = in.read(buff, 0, 2048);
}
// System.out.println(result);
Charset charset = Charset.forName("UTF-8");
result = charset.decode(charset.encode(result)).toString();
texte.setText(result);
in.close();
//System.out.println("Erreur la2");
}
}
} catch (Exception err) {
JOptionPane.showMessageDialog(this, "Erreur lors du chargement du fichier", "Error", JOptionPane.WARNING_MESSAGE);
}
}
My textarea is : texte.setText(result);
Do you have any idea?

If your file encoding is UTF-8 then simply read it like here
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
texte.setText(result);

The Charset.encode method expects a string in unicode format. In fact all strings in java are supposed to be unicode (utf16).
Do this
String substr = new String(buff, 0, read, "UTF-8");
And remove all the charset.encode/decode code.

Your line String substr = new String(buff, 0, read); should have been
String substr = new String(buff, 0, read,"UTF-8");
Constructor String(byte[] bytes, int offset, int length) constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

Related

Java compressing a .txt file

I am currently trying to write a program which reads in a compressed file which is written in bits or 0s and 1s, and convert them in to strings of 0s and 1s.
The School provided a class and method for reading 1 bit and converting that in to a character char. So to read and convert one bit to a char, all i need to do is type in my code:
char oneBit = inputFile.readBit();
in my main method.
How do I get my program to read over every bit within the compressed file and convert them to char? using the .readBit method? And how would I convert all the char 0s and 1s in to strings of 0s and 1s?
The readBit method:
public char readBit() {
char c = 0;
if (bitsRead == 8)
try {
if (in.available() > 0) { // We have not reached the end of the
// file
buffer = (char) in.read();
bitsRead = 0;
} else
return 0;
} catch (IOException e) {
System.out.println("Error reading from file ");
System.exit(0); // Terminate the program
}
// return next bit from the buffer; bit is converted first to char
if ((buffer & 128) == 0)
c = '0';
else
c = '1';
buffer = (char) (buffer << 1);
++bitsRead;
return c;
}
where in is the input file.
Try using this resource
Sample implementation.
public class BitAnswer {
final static int RADIX = 10;
public static void main(String[] args) {
BitInputStream bis = new BitInputStream("<file_name>");
int result = bis.readBit();
while( result != -1 ) {
System.out.print(Character.forDigit(result, RADIX));
result = bis.readBit();
}
System.out.println("\nAll bits read!");
}
}
public void compress(){
String inputFileName = "c://tmp//content.txt";
String outputFileName = "c://tmp//compressedContent.txt";
FileOutputStream fos = null;
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStream outputStream= null;
try (BufferedReader br = new BufferedReader(new FileReader(new File(inputFileName)))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
outputStream = new DeflaterOutputStream(byteArrayOutputStream); // GZIPOutputStream(byteArrayOutputStream) - use if you want unix .gz format
outputStream.write(sb.toString().getBytes());
String compressedText = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
fos=new FileOutputStream(outputFileName);
fos.write(compressedText.getBytes());
System.out.println("done compress");
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if (outputStream != null) {
outputStream.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
if(fos != null){
fos.close();
}
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("closed streams !!! ");
}
}

File Transfer malformed input

Currently trying to have the server send a file to the client.
I'm able to see the file being created in the client directory, but it won't send all the bytes. Sometimes its 90% of the bytes, and sometimes its not even 10 bytes.
I keep getting a message from the terminal window saying: "malformed input around byte...."
Here's the Server code for this section:
String cMessage;
DataInputStream input= new DataInputStream( remote_socket.getInputStream() );
File filename = new File(cMessage);
try {
input = new DataInputStream(new FileInputStream(filename));
DataOutputStream out = new DataOutputStream(remote_socket.getOutputStream());
byte[] buffer = new byte[(int) filename.length()];
int count;
while((count = input.read(buffer)) >0){
out.write(buffer, 0, count);
}
System.out.println("Sending " + cMessage + " that is " + filename.length());
out.flush();
} catch (IOException e) {
System.out.println(e + "......");
e.printStackTrace();
}
Output for the Server when running looks like:
Sending test.png that is 723915
Here's the Client for this section:
try {
BufferedReader reader= new BufferedReader(
new InputStreamReader(System.in) );
String message;
BufferedReader fileMessageReader= new BufferedReader(
new InputStreamReader(System.in) );
String fileMessage;
DataOutputStream output= new DataOutputStream(this.client_socket.getOutputStream() );
DataInputStream input = new DataInputStream(this.client_socket.getInputStream());
while(true) {
while( (message = reader.readLine()) != null ) {
System.out.println("1. For a text message. 2. For a file");
if (message.equals("2")) {
System.out.println("Name of file?");
fileMessage = fileMessageReader.readLine();
output.writeUTF(fileMessage);
try {
File filename = new File(fileMessage);
DataOutputStream fileOutput = new DataOutputStream(new FileOutputStream(filename));
byte[] buffer = new byte[1024];
int count;
while((count = input.read(buffer)) >0){
fileOutput.write(buffer, 0, count);
}
fileOutput.flush();
fileOutput.close();
} catch (IOException e) {
System.out.println(e + "...");
}
} else {
output.writeUTF( message );
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
while ((c = input.read()) != -1) {
output.write(c);
}
This piece is killing it. If you read javadoc carefully, rather than just checking method signature, you will see that read() reads a single byte from the input (it returns int only to be able to signal end of stream with -1). So you read byte as int, no big deal, but then you blindly write aforementioned int (4 bytes) into the output stream.
You should use read(byte[] b) instead and then write the whole array (or only part of it that was read in the last round).

Read complete file without looping in android

i need a solution for reading a text file which was stored in internal storage.
i don't want to read it line by line. without use looping how to read a complete text file and store it into a string.
BufferedReader br;
String line;
String data = "";
// String text="";
try {
br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "queue_mgr.txt")));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
}
You can use a large byte buffer and gain some efficiency:
try
{
InputStream in = new FileInputStream (from);
OutputStream out = new FileOutputStream (to);
// Transfer bytes from in to out
byte[] buf = new byte[1024 * 10]; // 5MB would be about 500 iterations
int len;
while ((len = in.read (buf)) > 0)
out.write (buf, 0, len);
in.close ();
out.close ();
}
}
catch (FileNotFoundException e)
{
...
}
catch (IOException e)
{
...
}

Android download txt from website without removing wrap

I need to download a .txt file from a website, the problem is the downloaded file doesn't respect the same line wrapping as the original file.
File:
Word1
Word2
Word3
File downloaded:
Word1Word2Word3
I use this method to download (this isn't mine) :
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream( MegaMethods.FolderPath+"downloadedfile.txt");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Try using a BufferedReader to read it in something like
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
responseData.append(line);
}
then output the lines as necessary. I'm no where near a station where I can test this so you might have to do some fiddling.

How to get intput stream from .txt file ( android )?

I want to read my data from my .txt file into a ReaderClass in android, fields are seperated by ";"
---- here is my solution of my last post:
public void cut()
{
try{
InputStream input =context.getResources().openRawResource(R.raw.textfile);
BufferedReader br = null;
br=new BufferedReader(new InputStreamReader(input,"iso-8859-1"));
String line = null;
while ((line = br.readLine()) != null) {
String[] decoupage= line.split(";");
String titre=decoupage[0];
String description=decoupage[1];
String reponse=decoupage[2];
String explication=decoupage[3];
String categorie=decoupage[4];
String etat=decoupage[5];
//test Logcat
Log.d("information ", " buffer");
Log.i("titre : ",titre);
Log.i("description : ",description);
Log.i("reponse : ",reponse);
Log.i("explication : ",explication);
Log.i("categorie : ",categorie);
Log.i("etat : ",etat);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
System.err.println("\n File not found");
}
//end
}
FileInputStream fis;
fis = openFileInput("sample.txt");
StringBuffer Content = new StringBuffer("");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
Content.append(new String(buffer));
}
you will get entire content in a string buffer ,convert it into string, then you can apply yourString.split(";") to get all values which you can keep in some array.

Categories