Please Will some one help me out i am trying to read an Arabic .txt file and it always give me the Arabic word like this "????? ???"
private String ReadArabic() {
String words="";
try {
InputStream stream = getAssets().open("arabwords.txt");
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
words = new String(buffer, "UTF-8");
words = words.replaceAll("(\\r|\\n)", "");
} catch (IOException e) {
// Handle exceptions here
}
return words;
}
Try using: "cp864" instead of "UTF-8"
Its possible that your console is not set to
properly display UTF-8 characters.
The configuration of that depends
on the IDE. You might need to configure the same there.
it worked by using "cp1256"
Thanks Evey one
private String ReadArabic() {
String words="";
try {
InputStream stream = getAssets().open("arabwords.txt");
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
words = new String(buffer, "cp1256");
words = words.replaceAll("(\\r|\\n)", "");
} catch (IOException e) {
// Handle exceptions here
}
return words;
}
Related
I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.
But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.
There is no method like .readString() in DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode contains ready sequence
The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
But I would actually advise you to rewrite you file with some known file format, like so:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
And read it like you would read any other file:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.
I am trying to write a new line to a text file in android.
Here is my code:
FileOutputStream fOut;
try {
String newline = "\r\n";
fOut = openFileOutput("cache.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.write(newline);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have tried \n, \r\n and I did also try to get the system property for a new line, neither of them work.
The data variable contains previously data from the same file.
String data = "";
try {
FileInputStream in = openFileInput("cache.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "ISO8859-1");
BufferedReader inRd = new BufferedReader(isr,8 * 1024);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
}
in.close();
data = inLine.toString();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I had the same problems, tried every trick in the book.
My problem: the newline's were written, but while reading they were removed:
while (readString != null) {
datax.append(readString);
readString = buffreader.readLine();
}
The file was read line by line and concatenated, so the newline's disappeared.
I did not look at the original file in Notepad or something because I didn't know where to look on my phone, and my logscreen used the code which removed the newline's :-(
So the simple soultion was to put it back while reading:
while (readString != null) {
datax.append(readString);
datax.append("\n");
readString = buffreader.readLine();
}
I executed a similar program and it worked for me. I observed a strange behavior though. It added those new lines to the file, however the cursor remained at the first line. If you want to verify, write a String after your newline characters, you will see that the String is written just below those new lines.
I was having the same problem and was unable to write a newline. Instead I use BufferdWritter to write a new line into the file and it works for me.
Here is a sample code sniplet:
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cache.txt",0));
BufferedWriter bwriter = new BufferedWriter(out);
// write the contents to the file
bwriter.write("Input String"); //Enter the string here
bwriter.newLine();
I'm relatively new to Java and I'm attempting to write a simple android app. I have a large text file with about 3500 lines in the assets folder of my applications and I need to read it into a string. I found a good example about how to do this but I have a question about why the byte array is initialized to 1024. Wouldn't I want to initialize it to the length of my text file? Also, wouldn't I want to use char, not byte? Here is the code:
private void populateArray(){
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("3500LineTextFile.txt");
} catch (IOException e) {
Log.e("IOException populateArray", e.getMessage());
}
String s = readTextFile(inputStream);
// Add more code here to populate array from string
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inputStream.length
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
Log.e("IOException readTextFile", e.getMessage());
}
return outputStream.toString();
}
EDIT: Based on your suggestions, I tried this approach. Is it any better? Thanks.
private void populateArray(){
AssetManager assetManager = getAssets();
InputStream inputStream = null;
Reader iStreamReader = null;
try {
inputStream = assetManager.open("List.txt");
iStreamReader = new InputStreamReader(inputStream, "UTF-8");
} catch (IOException e) {
Log.e("IOException populateArray", e.getMessage());
}
String String = readTextFile(iStreamReader);
// more code here
}
private String readTextFile(InputStreamReader inputStreamReader) {
StringBuilder sb = new StringBuilder();
char buf[] = new char[2048];
int read;
try {
do {
read = inputStreamReader.read(buf, 0, buf.length);
if (read>0) {
sb.append(buf, 0, read);
}
} while (read>=0);
} catch (IOException e) {
Log.e("IOException readTextFile", e.getMessage());
}
return sb.toString();
}
This example is not good at all. It's full of bad practices (hiding exceptions, not closing streams in finally blocks, not specify an explicit encoding, etc.). It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
Read the Java IO tutorial to learn how to read text from a file.
You are reading the file into a buffer of 1024 Bytes.
Then those 1024 bytes are written to outputStream.
This process repeats until the whole file is read into the outputStream.
As JB Nizet mentioned the example is full of bad practices.
Wouldn't I want to initialize it to the length of my text file? Also, wouldn't I want to use char, not byte?
Yes, and yes ... and as other answers have said, you've picked an example with a number of errors in it.
However, there is a theoretical problem doing both; i.e. setting the buffer length to the file length and using a character buffer rather than a byte buffer. The problem is that the file size is measured in bytes, but the size of the buffer needs to be measured in characters. This is normally fine, but it is theoretically possible that you will need more characters than the file size in bytes; e.g. if the input file used a 6 bit character set and packed 4 characters into 3 bytes.
To read from a file I usaully use a Scanner and a StringBuilder.
Scanner scan = new Scanner(new BufferedInputStream(new FileInputStream(filename)), "UTF-8");
StringBuilder sb = new StringBuilder();
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
sb.append("\n");
}
scan.close
return sb.toString();
Try to throw your exceptions instead of swallowing them. The caller must know there was a problem reading your file.
Edit: Also note that using a BufferedInputStream is important. Otherwise it will try to read bytes by bytes which can be slow.
Virtually every code example out there reads a TXT file line-by-line and stores it in a String array. I do not want line-by-line processing because I think it's an unnecessary waste of resources for my requirements: All I want to do is quickly and efficiently dump the .txt contents into a single String. The method below does the job, however with one drawback:
private static String readFileAsString(String filePath) throws java.io.IOException{
byte[] buffer = new byte[(int) new File(filePath).length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream(filePath));
f.read(buffer);
if (f != null) try { f.close(); } catch (IOException ignored) { }
} catch (IOException ignored) { System.out.println("File not found or invalid path.");}
return new String(buffer);
}
... the drawback is that the line breaks are converted into long spaces e.g. " ".
I want the line breaks to be converted from \n or \r to <br> (HTML tag) instead.
Thank you in advance.
What about using a Scanner and adding the linefeeds yourself:
sc = new java.util.Scanner ("sample.txt")
while (sc.hasNext ()) {
buf.append (sc.nextLine ());
buf.append ("<br />");
}
I don't see where you get your long spaces from.
You can read directly into the buffer and then create a String from the buffer:
File f = new File(filePath);
FileInputStream fin = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
String s = new String(buffer, "UTF-8");
You could add this code:
return new String(buffer).replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
Is this what you are looking for?
The code will read the file contents as they appear in the file - including line breaks.
If you want to change the breaks into something else like displaying in html etc, you will either need to post process it or do it by reading the file line by line. Since you do not want the latter, you can replace your return by following which should do the conversion -
return (new String(buffer)).replaceAll("\r[\n]?", "<br>");
StringBuilder sb = new StringBuilder();
try {
InputStream is = getAssets().open("myfile.txt");
byte[] bytes = new byte[1024];
int numRead = 0;
try {
while((numRead = is.read(bytes)) != -1)
sb.append(new String(bytes, 0, numRead));
}
catch(IOException e) {
}
is.close();
}
catch(IOException e) {
}
your resulting String: String result = sb.toString();
then replace whatever you want in this result.
I agree with the general approach by #Sanket Patel, but using Commons I/O you would likely want File Utils.
So your code word look like:
String myString = FileUtils.readFileToString(new File(filePath));
There is also another version to specify an alternate character encoding.
You should try org.apache.commons.io.IOUtils.toString(InputStream is) to get file content as String. There you can pass InputStream object which you will get from
getAssets().open("xml2json.txt") *<<- belongs to Android, which returns InputStream*
in your Activity. To get String use this :
String xml = IOUtils.toString((getAssets().open("xml2json.txt")));
So,
String xml = IOUtils.toString(*pass_your_InputStream_object_here*);
i am having a problem in reading a file from Flex. The file contains a base64encoded string. when i read the file i get the length as 47856 and the decoded base64 byte array length as 34157.
When i read the same File from java i get the length as 48068 and 35733 respectively.
What is the problem?
private function init():void{
var file:File = File.desktopDirectory.resolvePath("Files/sample.txt");
stream = new FileStream();
stream.open(file, FileMode.READ);
var str:String = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
str = str.replace(File.lineEnding, "\n");
contents.text = str;
fileName.text = file.name;
}
public function playSound(contents:String):void{
try{
var byteData: ByteArray;
byteData = new ByteArray();
byteData.writeUTFBytes(contents);
var dec:Base64Decoder = new Base64Decoder();
dec.decode(contents);
byteData = dec.toByteArray();
Alert.show("byte Array " + byteData.toString().length +" :: " +contents.length);
}
And this is my java code for reading the file...Whatever result i am expecting is achieved in the java side.
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
return Charset.defaultCharset().decode(bb).toString(); }
finally { stream.close();
}
}
Java Code where i am printing the length
byte[] decodedBase64 = new byte[byteLength];
String speexData = null;
try {
speexData = readFile(userDir +"//" +xmlFileName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("sa " + sa);
try{
decodedBase64= Base64.decodeToByteArray(speexData);
System.out.println("decodednase64 length " + decodedBase64.length +" :: " +speexData.length());
}
catch(Exception e){
}
You would have to post your java code to show what you're doing there, as well.
However, without knowing more, I could take a guess and say that when you replace the line ending, you may be removing a byte each time (if it was \r\n and you're making it \n, for example).