I created a csv file with the following format which I'm aiming to output to the device's sd card:
Ship Name,Scientist Name,Scientist Email,Sample Volume,Sample Colour,Longitude,Latitude,Material,Date
Each of the vales in the csv will be of type string except for the last value of date.
The name of the csv file is AnalysisData.csv
I've looked examples on Stackoverflow such as this, Export my data on CSV file from app android but this creates a new file which I don't want.
I have already added the opencsv jar to my project so just need a relevant example.
Does anyone have any advice on achieving this in Android?
Try with this code snippet :
String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "AnalysisData.csv";
String filePath = baseDir + File.separator + fileName;
File f = new File(filePath);
CSVWriter writer;
// File exist
if(f.exists()&&!f.isDirectory())
{
mFileWriter = new FileWriter(filePath, true);
writer = new CSVWriter(mFileWriter);
}
else
{
writer = new CSVWriter(new FileWriter(filePath));
}
String[] data = {"Ship Name", "Scientist Name", "...", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").formatter.format(date)});
writer.writeNext(data);
writer.close();
Related
I'm new to programming in android. I'm trying to create a csv file in the shared storage of the android device. I then want to add lines to that file based on user inputs. It looks like with android 11 the process of creating and editing file on shared storage has changed and i'm quite confused on how to accomplish it.
So far I have been able to create a csv file but I can't seem to edit it in any way. This is the code I used to create the csv file:
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Uri baseDirUri = Uri.fromFile(baseDir);
String fileName;
String noteFile;
private void createFile() {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/csv");
String currentTime = getPhoneTime();
fileName = "notes_" + currentTime + ".csv";
intent.putExtra(Intent.EXTRA_TITLE, fileName);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, baseDirUri);
startActivityForResult(intent, 1);
noteFile = baseDir.getAbsolutePath() + "/" + fileName;
writeToCsv("Time;ROS Time;Event;Team;Description;Ticket");
}
I then use openCSV to try and write to the csv File:
private void writeToCsv(String line) {
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(noteFile);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
writer.writeNext(line.split(";"));
// closing writer connection
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the file is empty when I go to view it. What am I doing wrong? Thanks for the help!
I create pdf file using itext. This is the code:
private void createPdf() throws FileNotFoundException, DocumentException ,IOException {
// create folder to save the pdf
// new FileOutputStream("/Internal storage/")
File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "FolderName");
if (!pdfFolder.exists()) {
pdfFolder.mkdir();
Log.i("creat", "Pdf Directory created");
}
// end creat folder
// create file name using todaydate.
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
File myFile = new File(pdfFolder +"/"+ timeStamp + ".pdf");
OutputStream output = new FileOutputStream(myFile);
//Step 1
Document document = new Document();
//Step 2
PdfWriter writer = PdfWriter.getInstance(document, output);
//Step 3
document.open();
//Step 4 Add content
document.add(new Paragraph("\n\nTAX INVOICE.\n"));
document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n*THIS IS COMPUTER GENERATED INVOICE NO SIGNATURE REQUIRED."));
//Step 5: Close the document
document.close();
UploadToServer(myFile,userid,username);
}
Now in the function UploadToServer(myFile, userid, username); as it showing am giving the myFile Type File and, userid and username Type String.
I want this function to upload the pdf file let say to this folder "www.ccc.com/pdffiles", and create a row in pdffile database content the URL to that pdf file, username, and userid
also from another activity i want to view pdf file from URL where I will get the url from pdffile database
I need to save file into internal storage, an then read it.
For save it i do something like this:
// Create directory into internal memory;
File mydir = getActivity().getDir("modelli", Context.MODE_PRIVATE);
File a = new File(mydir, obj_id);
a.mkdir();
File b = new File(mydir, obj_id);
if (obj_type != "modello"){
b = new File(a,obj_type);
b.mkdir();
}
String filename = "";
if(obj_imageName != null)
{
filename = obj_imageName + "." + getFileExtension(urlString);
}
else
{
filename = getFileName(urlString);
}
final File file = new File(b, filename);
file.createNewFile();
but I don't know how read it, with this I get an error (contains a path separator):
File mydir = getActivity().getDir("app_modelli/2/images", Context.MODE_PRIVATE);
where is the mistake? is correct my approach for write file?
You better put them in internal files dir. Both for writing and reading you could use a File object like:
String fileName = "info.txt";
File file = new File ( getInternalFilesDir() + "/" + fileName);
At the moment your code only creates a file with length 0. You are not writing/saving anything to it.
I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
How can I create file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) Thank You
Using this code you can write to a text file in the SDCard.
Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.
An example from the android documentation:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt
try
{
File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
//File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n\n");
writer.flush();
writer.close();
Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
First create a Project With PdfCreation in Android Studio
Then Follow below steps:
1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
System.out.print(myDir.toString());
myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Open Document for Writting into document
document.open(); // User Define Method
addMetaData(document);
try {
addTitlePage(document);
} catch (DocumentException e) {
e.printStackTrace();
} // Close Document after writting all content
document.close();
5. public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException
{ // Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
prHead.setFont(titleFont); // Add item into Paragraph
prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f); // Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable); // Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: john_pit#gmail.com \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile); // Create new Page in PDF
document.newPage();
}
I'm using Kotlin here
Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example
var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
strwrt=FileWriter(File("sdcard/${NamaFile}"))
strwrt.write(teks)
strwrt.close()
after that, you can access File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folders.