android studio: reading a csv with Japanese character using opencsv - android

I have a csv file in my assets file and would like to read it using opencsv
I successfully to get and read the file but fail in printing it,
and the string are displayed as the screen capture below.
My csv is save as Unicode from excel
My code in reading and logging csv:
AssetManager assetManager = context.getAssets();
try {
InputStream csvStream = assetManager.open("data.csv");
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String [] nextLine;
Log.d("test","reading csv");
while ((nextLine = csvReader.readNext()) != null) {
// nextLine[] is an array of values from the line
Log.d("test",nextLine.toString() + " etc...");
String[] temp= nextLine.toString().split(",");
for(int i=0; i<nextLine.length;i++){
Log.d("test", nextLine[i]);
}
break;
}
} catch (FileNotFoundException e) {
Log.d("test","fail read csv");
e.printStackTrace();
} catch (IOException e) {
Log.d("test","io exception csv");
e.printStackTrace();
}
the csv file's text
and the screen capture in the logcat:

This depends on the encoding of the file.
With any luck, it's in UTF-8. You need to tell your InputStreamReader to use UTF-8 else it'll probably fall back to ISO 8859_1 (ISO-Latin-1).
You can do this like so:
InputStreamReader csvStreamReader = new InputStreamReader(csvStream, "UTF-8");
If your file is encoded in another format, you'll need to specify that.
Edit: After a re-read, I see you exported from Excel. You'll need to tell Excel to export in UTF-8 instead of whatever it defaults to (likely Windows-1252).

Related

write text file in res/raw folder

I have a text file in folder res/raw name "pass.txt" and some data in it i want to delete this data and enter new data in it.... is it possible to write data on it?? otherwise what is correct path to store my text file so i can easily read/write data on it.... and what is the code to read and write data from it?? below is the code through which i can only read data from this text file
InputStream fr = getResources().openRawResource(R.raw.pass);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
String s=br.readLine().toString().trim();
Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime.
Look at Internal or External Data Storage APIs to read write files.
https://developer.android.com/training/basics/data-storage/files.html
you can use Android internal storage to Read and write file ... as res/raw is only Read only..you can not change content at runtime.
Here is the code:
Create file
String MY_FILE_NAME = “mytextfile.txt”;
// Create a new output file stream
FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);
Read from file:
public void Read(){
static final int READ_BLOCK_SIZE = 100;
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Write to file:
public void Write(){
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("TEST STRING..");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}

How to show "®" read from text file in assets directory?

Does anybody know the best way to show the "®" symbol when read from a text file in the assets directory? I've tried replacing the "®" symbol with &® or ® or \u00AE, but none of these work.
Is the only solution to define it as html?
Here's the code I'm using to read the text file from assets:
mTextViewTermsConditions = (TextView) findViewById(R.id.textView_terms_conditions);
StringBuffer stringBufferEula = new StringBuffer();
try
{
InputStream inputStream = getAssets().open("eula");
BufferedReader f = new BufferedReader(new InputStreamReader(inputStream));
String line = f.readLine();
while (line != null)
{
Logger.d(line);
stringBufferEula.append(line);
line = f.readLine();
}
}
catch (IOException e)
{
Logger.e(e.toString());
e.printStackTrace();
}
mTextViewTermsConditions.setText(stringBufferEula);
This is an encoding problem. Make sure that your asset file is stored with UTF-8 encoding.
Answer thanks to Ted Hopp above:
Make sure that the text file is encoded UTF-8.

What's wrong with my read and write of the file in Android app's assets?

Code first:
AssetManager mgr = DeviceListActivity.this.getApplicationContext().getAssets();
try {
Log.e("Glenn:", address);
FileOutputStream fout = mgr.openFd("device/device_address.txt").createOutputStream();
PrintWriter _fout = new PrintWriter(fout);
_fout.println(address);
Log.e("Glenn", address);
_fout.close();
fout.close();
InputStream fin = mgr.open("device/device_address.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
address = br.readLine();
try {
Log.e("Glenn:", address);
} catch (NullPointerException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
Log.e("Glenn", "error with OutputStream");
}
The value of address printed by the first two Log.e() calls is the right value, which actually is a device MAC address. However, when I was trying to test the value of address read from the file, which had just been written, NullPointerException has been caught within the Log.e() call. This means the value read from the file is NULL. Can anyone point out what's wrong with the code?
You cannot write in your app's asset file. You have only read but not write permissions. AssetManager only provides methods to read the files from your app's asset folder.

Reading int value from txt file on SD card android

So in this app I made, The user makes a project and when they save, the number of frames is saved to numberFrames.txt on the SD card. Then I retrieve the file in another class. Only thing is that nFrames = 50 when i show a toast of nFrames to the screen after I run this code. The only initializing of nFrames I do is to zero right above this code, which is located in the onCreate().
File sdcardLocal = Environment.getExternalStorageDirectory();
File dir = new File (sdcardLocal.getAbsolutePath() + "/Flipbook/"+customizeDialog.getTitle()+"/");
dir.mkdirs();
File fileNum = new File(dir, "numberFrames.txt");
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileNum);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(myFileWriter);
try {
String text = bitmaps.size()+"";
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
I retrieve the file like this. I have no idea where this "50" value for nFrames came from as there are no loops around this and I know for sure that the particular project saved has only 3 frames. Why is this?
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(mFolderDialog.getPath()+"/numberFrames.txt"));
bis = new BufferedInputStream(is);
nFrames = bis.read();
}catch (IOException e) {
e.printStackTrace();
}
You are writing out a string, and then reading the first byte as an integer. 50 is the ascii code for the '2' character.
You can use BufferedReader.readLine to read the entire first line of the file as a String, and then Integer.parseInt to convert that to an integer.
Also, I would take a closer look at your application's workflow. You don't give much information, but saving a file with a single integer value to the sdcard has a certain "smell" to it :). Have you looked at using a database, or maybe store the text file in your application's directory instead?

write and read strings to/from internal file

I see a lot of examples how to write String objects like that:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
but not how to read them back from internal application file. Most of examples assume specific string length to calculate byte buffer but I do not know what the length will be. Is there an easy way to do so? My app will write up to 50-100 strings to the file
Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.
You can use DataOutputStream.writeUTF() and DataInputStream.readUTF() instead as these methods put the length of the strings in the file and read back the right number of characters automatically.
In an Android Context you could do something like this:
try {
// Write 20 Strings
DataOutputStream out =
new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
for (int i=0; i<20; i++) {
out.writeUTF(Integer.toString(i));
}
out.close();
// Read them back
DataInputStream in = new DataInputStream(openFileInput(FILENAME));
try {
for (;;) {
Log.i("Data Input Sample", in.readUTF());
}
} catch (EOFException e) {
Log.i("Data Input Sample", "End of file reached");
}
in.close();
} catch (IOException e) {
Log.i("Data Input Sample", "I/O Error");
}

Categories

Resources