Reputation: 853
I am trying to convert ansii(latin-5) text file to utf-8 text file in a directory. I made a small mechanish to understand if the file is ansii or utf-8 however when i try to change ansii file to utf-8 program deletes all values in the text. Where am i doing wrong?
Thanks in advance.
Here is my code:
package altyazi;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
public class operation{
public static int howmany =0;
public static int howmanysmalli=0;
public static double ratio;
File myFile;
public static void koddegıstır(String myfile) throws IOException{
File file = new File(myfile);
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray);
fis.close();
int[] freqs = new int[256];
for(byte b: bytesArray){
freqs[b&0x0ff]++;
}
howmany = freqs[107]+freqs[75];
howmanysmalli=freqs[253];
System.out.println("Character \"k\" appears " + howmany +" times in the text "+myfile);
ratio = (double)howmany/(double)bytesArray.length;
System.out.println("How many: "+howmany);
System.out.println("Length: "+bytesArray.length);
System.out.println("Ratio: "+ratio);
//Cp1254
if(ratio<0.01){
System.out.println("Text file is probably not turkish");
}else{
System.out.println("Text file is probably turkish");
if(howmanysmalli>20){
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(myfile),
"ISO-8859-9"));
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
myfile), "UTF-8"));
try {
while ((line = br.readLine()) != null) {
out.write(line);
out.write("\n");
}
} finally {
br.close();
out.close();
}
}else{
System.out.println("Passed as utf-8");
}
}
}
}
Upvotes: 0
Views: 183
Reputation: 310913
You are overwriting the file when you create the FileOutputStream
. This creates an empty file. You need to write to a new file, and delete the old one and rename the new one when complete.
Upvotes: 3