how to changes files name dynamically in android studio? - android-studio

problem- only one files is save to the external storage with global name.
How to get the idea to changes the file name dynamically changes.
private String FILE_NAME = "billReceipt"; // I declared this variable as globally
encodedBase64 = response;
try{
File filePath = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/"+ file_name+".pdf");
FileOutputStream os = new FileOutputStream(filePath, true);
byte [] decodeBase64 = android.util.Base64.decode(encodedBase64, Base64.DEFAULT); //decoded the encoded string
os.write(decodeBase64);
os.flush();
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}

Related

How fix System.FormatException reading data from text file to a listbox

My code takes data from form application and displays the result in a listbox and save the data in a file. When next I load the code it should read the data from the file and populate the listbox. I am have a System.FormatException Input string not in correct format.
The code works until I am ready to read the file. I have removed the whitespaces and the dollar sign but the problem is still there. Please any help will be appreciated.
My FileIO class code below
public static class FileIO
{
const string path = "Customers.txt";
// writes data from the array to the file
public static void WriteData(List<Customer> customers)
{
FileStream fs = null;
StreamWriter sw = null;
try
{
// open the file for writing; overwrite old content
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
// write data
foreach (Customer item in customers)
sw.WriteLine(item.DisplayCustomersInfo("|"));
}
catch (Exception ex)
{
MessageBox.Show("Error while writing to the file: " +
ex.Message, ex.GetType().ToString());
}
finally
{
if (sw != null) sw.Close(); // also closes fs
}
}
// reads data from the file, puts in a list, and returns it
public static List<Customer> ReadData()
{
List<Customer> customers = new List<Customer>();
FileStream fs = null;
StreamReader sr = null;
string line; // for reading
string[] columns; // result from splitting the line
// open the file for reading and read number into data
try
{
fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
sr = new StreamReader(fs);
while (!sr.EndOfStream) // while there is data in the file
{
line = sr.ReadLine(); // read the next line
line.Trim();
columns = line.Split(','); // split line into substring from line with comma delimiters
Customer c = new Customer(Convert.ToInt32(columns[0]), columns[1], Convert.ToChar(columns[2]),
Convert.ToDecimal(columns[3].Remove(0, 1)));//this is where I think the problem is.
customers.Add(c);
}
}
catch (FormatException)
{
MessageBox.Show("File contains bad format data. Aborting reading");
}
catch (Exception ex)
{
MessageBox.Show("Error while reading the file: "
+ ex.Message, ex.GetType().ToString());
}
finally
{
// close the file if open
if (sr != null) sr.Close(); //file stream gets closed too
}
return customers;
}
}
Below is the text file.
12345|RRRRR|R|$58.05
12345|RRRRR|R|$58.05
12345|RRRRR|R|$58.05
12345|RRRRR|R|$58.05
12345|RRRRR|R|$58.05
12345|CCCCC|C|$60.05
12345|CCCCC|C|$60.05
12345|CCCCC|C|$60.05
12345|CCCCC|C|$60.05
12345|CCCCC|C|$60.05
12345|IIIII|I|$116.09
12345|IIIII|I|$116.09
12345|IIIII|I|$116.09
12345|IIIII|I|$116.09
12345|IIIII|I|$116.09
12345|IIIII|I|$116.09
I have used , and ; as delimiters prior to using |.
I expect to read data from the file and populate the listbox and add more data.

cannot access the file because it is using by another program Error

I have been fighting with this issue since last week.still not able to solve.
i am sending file to client machine once i get in server automatically.but so many time when i handle file it throw an error that Cannot access the file because it is using by another program.
below my code
private static string SaveFileStream(string filePath, Stream stream, string Filename1)
{
string localresponse;
try
{
//this.SaveFileStream(System.Configuration.ConfigurationSettings.AppSettings[fileToPush.FileType].ToString() + "\\" + fileToPush.FileName, new MemoryStream(fileToPush.Content));
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Dispose();
}
FileInfo info = new FileInfo(filePath);
ExtractFile(info);
localresponse = "Successful";
}
catch (Exception ex)
{
localresponse = ex.Message;
}
return localresponse;
}

JXLS unable to output excel to servlet for user download

Hello im trying to output an excel file generated from a template xls using jxls library but I dont find the way to do so.
My code look like this:
ServletContext contexto = request.getServletContext();
String path = contexto.getRealPath("/lib/xlsx/plantilla.xlsx");
Conexion conexion = new Conexion();
List<Conexion> conexiones = new ArrayList<Conexion>();
ResultSet rs = CargarConsultas.ejecutarConsulta("CONS_GET_TABLA_CONEXION");
try {
while(rs.next()) {
conexion.setIp(rs.getString("ori_ip"));
conexion.setMac(rs.getString("ori_mac"));
conexion.setUrl_destino(rs.getString("url_dest"));
conexion.setSolicitud(rs.getString("time_stamp_solicitud"));
conexion.setUser_id(rs.getString("user_id"));
conexion.setSubida(rs.getString("icoming"));
conexion.setBajada(rs.getString("outgoing"));
conexion.setAutorizacion(rs.getString("time_stamp_autorizacion"));
conexion.setRenovacion(rs.getString("time_stamp_renovacion"));
conexion.setFin_sesion(rs.getString("time_stamp_fin_sesion"));
conexion.setGw_adress(rs.getString("gw_address"));
conexion.setGw_port(rs.getString("gw_port"));
conexiones.add(conexion);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File salida = new File(path);
InputStream is = new FileInputStream(salida);
try (FileOutputStream os = new FileOutputStream("salida.xlsx")) {
Context context = new Context();
context.putVar("conexiones", conexiones);
JxlsHelper.getInstance().processTemplate(is, os, context);
} catch (Exception e) {
e.printStackTrace();
}
Please let me knoew if you know how to output it and no save it to server disk.The code works fine. Thanks alot

Android 6 get path to downloaded file

I our app (Xamarin C#) we download files from a server. At the end of a succeful download we get the URI to the newly-downloaded file and from the URI we get the file path:
Android.Net.Uri uri = downloadManager.GetUriForDownloadedFile(entry.Value);
path = u.EncodedPath;
In Android 4.4.2 and in Android 5 the uri and path look like this:
uri="file:///storage/emulated/0/Download/2.zip"
path = u.EncodedPath ="/storage/emulated/0/Download/2.zip"
We then use path to process the file.
The problem is that in Android 6 (on a real Nexus phone) we get a completely different uri and path:
uri="content://downloads/my_downloads/2802"
path="/my_downloads/2802"
This breaks my code by throwing a FileNotFound exception. Note that the downloaded file exists and is in the Downloads folder.
How can I use the URI I get from Android 6 to get the proper file path so I can to the file and process it?
Thank you,
donescamillo#gmail.com
I didn't get your actual requirement but it looks like you want to process file content. If so it can be done by reading the file content by using file descriptor of downloaded file. Code snippet as
ParcelFileDescriptor parcelFd = null;
try {
parcelFd = mDownloadManager.openDownloadedFile(downloadId);
FileInputStream fileInputStream = new FileInputStream(parcelFd.getFileDescriptor());
} catch (FileNotFoundException e) {
Log.w(TAG, "Error in opening file: " + e.getMessage(), e);
} finally {
if(parcelFd != null) {
try {
parcelFd.close();
} catch (IOException e) {
}
}
}
But I am also looking to move or delete that file after processing.
May you an build your URI with the download folder :
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toURI();
It's work. #2016.6.24
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals( action)) {
DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if(c != null) {
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String downloadFileUrl = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
startInstall(context, Uri.parse(downloadFileUrl));
}
}
c.close();
}
}
}
private boolean startInstall(Context context, Uri uri) {
if(!new File( uri.getPath()).exists()) {
System.out.println( " local file has been deleted! ");
return false;
}
Intent intent = new Intent();
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction( Intent.ACTION_VIEW);
intent.setDataAndType( uri, "application/vnd.android.package-archive");
context.startActivity( intent);
return true;
}

Convert office document to pdf and display it on the browser

Please see the update question below (not the top one).
I tried to open any document type (especially PDF) on Liferay using this function. But I always get message Awt Desktop is not supported! as stated on the function. How can I enable the Awt Desktop? I tried searching over the internet and found nothing. Anyone help, pls? Thanks.
public void viewFileByAwt(String file) {
try {
File File = new File(getPath(file));
if (File.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(File);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
//File is not exists
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Source: http://www.mkyong.com/java/how-to-open-a-pdf-file-in-java/
UPDATE
As you see the code below, both mode (1 for download and 2 for preview) is working pretty well, but unfortunately the second mode (preview mode) is works only for PDF.
Now what I want to do is, while user clicking the preview button, files another than PDF (limited only for extension: DOC, DOCX, XLS, XLSX, ODT, ODS) must be converted to PDF first, and then display it on the browser with the same way as below code explained. Is it possible to do that? If it's too hard to have all of the converter on a function, then on a separated function each extension would be fine.
public StreamedContent getFileSelected(final StreamedContent doc, int mode) throws Exception {
//Mode: 1-download, 2-preview
try {
File localfile = new File(getPath(doc.getName()));
FileInputStream fis = new FileInputStream(localfile);
if (mode == 2 && !(doc.getName().substring(doc.getName().lastIndexOf(".") + 1)).matches("pdf")) {
localfile = DocumentConversionUtil.convert(doc.getName(), fis, doc.getName().substring(doc.getName().lastIndexOf(".") + 1), "pdf");
fis = new FileInputStream(localfile.getPath());
}
if (localfile.exists()) {
try {
PortletResponse portletResponse = (PortletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletResponse res = PortalUtil.getHttpServletResponse(portletResponse);
if (mode == 1) res.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getName() + "\"");
else if (mode == 2) res.setHeader("Content-Disposition", "inline; filename=\"" + doc.getName() + "\"");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setContentType(getMimeType(localfile.getName().substring(localfile.getName().lastIndexOf(".") + 1)));
res.flushBuffer();
OutputStream out = res.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
buffer = new byte[4096];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Liferay is a portal server; its user interface runs in a browser. AWT is the Java 1.0 basis for desktop UIs.
I don't think AWT is the way to display it.
Why can't you open the file and stream the bytes to the portlet using the application/pdf MIME type?
You have to first install openoffice on your machine
http://www.liferay.com/documentation/liferay-portal/6.1/user-guide/-/ai/openoffice
After configuring openoffice with liferay, you can use DocumentConversionUtil class from liferay to convert documents.
DocumentConversionUtil.convert(String id, InputStream is, String sourceExtension,String targetExtension)
Above code will return inputstream. After this conversion you can show pdf in your browser
Hope this helps you!!

Resources