I want to read CSV file. The problem is when i print a value of 0 or any other index the awkward result shown as you can see on snapshot. Snapshot attached.
Read value from this code:
InputStream inputStream = getResources().openRawResource(R.raw.stats);
FileReader csvFile = new FileReader(inputStream);
List<String[]> scoreList = csvFile.read();
for(String[] scoreData:scoreList ) {
Toast.makeText(this, scoreData[1], Toast.LENGTH_SHORT).show();
}
FileReader class:
package com.example.zohaib.ultimatesmsblocker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileReader {
InputStream inputStream;
public FileReader(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
CSV file:
The file you're trying to load is not a CSV, but a XLSX.
Not every Excel file is a CSV file. You need to export it to a CSV using Excel.
Excel's .xlsx files are actually XML files in certain format packed in ZIP. The PK you see as the first two letters represent the ZIP header.
Related
I have a base64 string which when decoded online using this website gives a zip file. When the zip file is downloaded it is password protected.
In my case, I know the password but I am not able to convert base64 to a zip file and also open it and read it in Android.
I used this answer on stack overflow but I am getting an error
Error: "java.util.zip.ZipException: Not in GZIP format"
I need a solution where I have the base64 String that it should decode into a zip file and then read the content of this zip file using the given password which has XML data.
Here is the code I have used so far:
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
public class GzipUtil {
public static void unzip() throws Base64DecodingException {
String encoded = "PUT BASE 64ENCODED GZIPPED STRING HERE";
byte[] compressed = Base64.decode(encoded);
String data = new String(compressed);
//System.out.println(data);AAAA";
if ((compressed == null) || (compressed.length == 0)) {
throw new IllegalArgumentException("Cannot unzip null or empty bytes");
}
if (!isZipped(compressed)) {
System.out.println(compressed);
}
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
try (InputStreamReader inputStreamReader =
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8)) {
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
StringBuilder output = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
output.append(line);
System.out.println(output.toString());
}
}
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to unzip content", e);
}
}
public static boolean isZipped(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC))
&& (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}
Please help!
I am trying to open a CSV file downloaded into internal storage for reading purpose alone. This is the code I have used:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.FileInputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
try {
String FileName = "/storage/emulated/0/Download/MyDocument.csv";
FileInputStream fis = openFileInput(FileName);
fis.read();
fis.close();
Toast.makeText(getBaseContext(),"File Access Permitted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(),"File Access Denied",Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
While the file is downloaded and I am able to open it in File Manager, the above code does not work. How do I achieve the required functionality?
As per this stackoverflow question's accepted answer, you could try this:
public String readFileFromDownloads(String fileName) {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!downloadsDir.exists()) return null;
File file = new File(downloadsDir, fileName);
if (!file.exists()) return null;
try {
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
fileContent.append(line);
fileContent.append('\n');
}
br.close();
return fileContent.toString();
} catch (IOException ex) {
//Handle error
return null;
}
}
And then call readFileFromDownloads("MyDocument.csv"); from inside your onClick(); method.
Also, you might need to add android.permission.READ_EXTERNAL_STORAGE to your Manifest and handle Android 6.0 new permission system as per Android Docs.
I've been getting the following error when I attempt to run an android application that inputs data from a text file.
"java.io.fileNotFoundException: /File.txt: open failed:ENOENT (No such file or directory)"
The file in question is in the Eclipse project folder.
I also tried putting it in the assets folder as well as several others.
Here is the code in question:
File file = new File("File.txt");
TestOutput = new ArrayList<String>();
String x = "";
try
{
Scanner scanner = new Scanner(file);
while (sc.hasNextLine())
{
x = sc.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
So far I have attempted to use a wrapper class to no avail, the code of which is below:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileGet
{
ArrayList<String> TestOutput = new ArrayList<String>();
public FileGet() {
}
public ArrayList<String> getFile() {
File file = new File("TestOutput.txt");
TestOutput = new ArrayList<String>();
try
{
Scanner scanner = new Scanner(file);
String x = "";
while (scanner.hasNextLine())
{
x = scanner.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return TestOutput;
}
}
That code works fine outside of the android application. Any advice/responses would be greatly appreciated.
Try this, the string named "line" is the string where all the TextFile is read.
Put the .txt file under /resources/raw folder.
InputStream is = getResources().openRawResource(R.raw.name_of_file);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line = null;
try {
while ((line = r.readLine()) != null)
total.append(line);
} catch (IOException e) {
e.printStackTrace();
}
line = total.toString();
i am working on an image gallery app in which i am loading images from URL so i have saved some image URLs in a text file and i am trying to read URLs from text file to ArrayList<String> but i am not able to load images in my app.
i tried this: but not works images are not loading
package com.nostra13.example.universalimageloader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class Constants {
public static List<String> LIST = new ArrayList<String>();
public void parseFile() {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("link.txt"));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static final String[] IMAGES = LIST.toArray(new String[LIST.size()]);
private Constants() {
}
public static class Config {
public static final boolean DEVELOPER_MODE = false;
}
public static class Extra {
public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
}
}
but if i add URLs manually like this: it works.
public static final String[] IMAGES = new String[] {
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
};
but i want to add text from text file (sdcard/file.txt) instead of manually adding.
Well, did you try and use Log.d() to post the lines of text that is being read from the file?
My best guess is that it's not reading the text file correctly, or perhaps formatting it wrongly (missing spaces perhaps, so it thinks its 1 big string?)
Try with this code:
public void parseFile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"link.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
The call to Environment.getExternalStorageDirectory() will return the path of SD card, and the path of declared variable file is relative to the root of SD card. If the file on a folder, you should declare:
File file = new File(sdcard,"data/com.myapplication.example/images/link.txt");
I am trying to write to a text file a list of names. It is written one line at a time and I have a class for Writing to File and Reading from it.
Here is the class:
package com.example.mobiledayoff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
public class userListIO {
Context fileContext;
public userListIO(Context fileContext){
this.fileContext=fileContext;
}
public void writeItems(String fileName, String name){
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer =
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
writer.write(name + ls);
} catch (Exception e){
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<CharSequence> readItems(String filename){
ArrayList<CharSequence> list = new ArrayList<CharSequence> ();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fileContext.getApplicationContext().openFileInput(filename)));
String line;
while((line = br.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
I use this class to write a line from user input (EditText) to the file. And then I read from file and Display contents of the file in another EditText. Here is how I do it:
public void addUser(View view){
EditText text = new EditText(this);
text = (EditText)findViewById(R.id.add_user_text);
String name = text.getText().toString();
String filename = "userList.txt";
userListIO messenger = new userListIO(this);
messenger.writeItems(filename, name);
text.setText("");
ArrayList<CharSequence> list = messenger.readItems(filename);
EditText editText = (EditText) findViewById(R.id.debug_text);
String info = "";
int count = 0;
for (CharSequence item: list){
info += item.toString();
count++;
}
info += "; there are " + count + " lines";
editText.setText(info);
}
My main problem is that it seems that file gets overwritten each time I write into it and so I always have 1 line. Do you guys know how to fix this? By fix I mean: How to append to the file if it already exists or create one if it doesn't exist.
Also I found out that after I close and reopen an app, the file does not exist. How to create and save a file, so that after closing and reopening I could still use the data stored there?
p.s. Read/Write was taken from here:
The best way to store user input data for later work
Change
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
to
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND)));
This will combine the MODE_PRIVATE flag aswell as the MODE_APPEND flag.
P.S. You should get away from opening and closing a stream everytime you write a line. This produces a lot of overhead and rather should you try to keep the stream opened until all your data has been processed.