How to prevent file overwriting? - file

I am working on an Arduino project using processing. There are some sensor values which should be logged, but unfortunately my processing code rewrites the file after each cycle so that I get the last sensor value only. How do I prevent this from happening? I am using the ordinary method by the way. PrintWriter command followed by createWriter.

You need to specify that you want to append to the file (otherwise, it will just overwrite). Something like this:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
out.println("the text");
}
catch (IOException e) {
// couldn't open file
}
The true at the end of the PrintWriter line specifies appending.

Related

How to generate qrcode in codename one

I'm trying to generate qrcode code in my application with qrgen and then saved in specific file but there is a problem in the libary 'java.io.FileOutputStream' where it can not be found. i want to know how to replace the libary and if there is another way to generate qrcode please share it with me
ByteArrayOutputStream out =QRCode.from(s).to(ImageType.PNG).stream();
try {
FileOutputStream fout = new FileOutputStream(new File(
"C:\\Users\\Public\\Pictures\\Sample Pictures\\QR_Code.JPG"));
fout.write(out.toByteArray());
fout.flush();
fout.close();
} catch (Exception e) {
// Do Logging
}
That isn't supported. Mobile devices don't have a file system in the way desktops have so this logic just won't work. There is a file system but it's to a large part private to the application, see: https://www.codenameone.com/manual/files-storage-networking.html

Image always missing in the received message while sharing an image in Codename One

I am generating an image that is saved in FileSytemStorage.getAppHomePath() dir. I now need to share it via Email, SMS ... That's why I am using the following code (based on Codename One documentation) in my action method :
long time = new Date().getTime();
String fullOutputPath = FileSystemStorage.getInstance().getAppHomePath()
+ "Montage_" + Long.toString(time) + ".png";
// Save the image with the ImageIO class
try (OutputStream os = FileSystemStorage.getInstance().openOutputStream(fullOutputPath)){
ImageIO.getImageIO().save(montage.getMontageImage(), os, ImageIO.FORMAT_PNG, 1.0f);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Enable image sharing (outside the try/catch so that the outputstream in closed for sure)
if (FileSystemStorage.getInstance().exists(fullOutputPath)) {
Dialog.show("Saved", "Photo collage saved to " + fullOutputPath
+ " (file size = " + FileSystemStorage.getInstance().getLength(fullOutputPath) +" B)", "OK", null);
//Photo collage saved to file://home/Montage_14669... .png (file size = 50387B)
findValidateMontageShareButton3().setImageToShare(fullOutputPath, "image/png");
// Null pointer exception
So in that way I get a NPE and if I don't test if the file does exist there is no NPE but the image is still missing (both in the simulator and on the device).
The stack trace is as follows :
java.lang.NullPointerException
at userclasses.StateMachine.onPage3_ValidateMontageShareButton3Action(StateMachine.java:852)
at generated.StateMachineBase.handleComponentAction(StateMachineBase.java:757)
at com.codename1.ui.util.UIBuilder$FormListener.actionPerformed(UIBuilder.java:2835)
at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:459)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:362)
at com.codename1.ui.Button.fireActionEvent(Button.java:411)
at com.codename1.ui.Button.released(Button.java:442)
at com.codename1.ui.Button.pointerReleased(Button.java:530)
at com.codename1.ui.Form.pointerReleased(Form.java:2627)
at com.codename1.ui.Form.pointerReleased(Form.java:2563)
at com.codename1.ui.Component.pointerReleased(Component.java:3158)
at com.codename1.ui.Display.handleEvent(Display.java:2025)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1067)
at com.codename1.ui.Display.mainEDTLoop(Display.java:996)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
It looks that the file my app is generating is not accesible to the sharing app. Do I have to add any extra permission as advised here for Android ?
Please note : I don't know if it is related to this problem but I cannot access to Codename One Settings menu from Eclipse anymore (maybe since upgrade to CN1 lib v 115)
Any help appreciated,
Cheers
So here is part of the answer which works in the simulator (ie the image appears in the fake email client => see image below).
So it appears that the share button cannot be set up in the action method (ie the method that is triggered when the user click on the share button). It has to be set up previously.
Consequently, in the beforeShow method my code reads as follows :`
FontImage.setMaterialIcon(findValidateMontageShareButton3(), FontImage.MATERIAL_CHECK_CIRCLE);
final long time = new Date().getTime();
// We generate the montage filename JPG otherwise it cannot be sent
montage.setMontageFullPath(FileSystemStorage.getInstance().getAppHomePath()
+ "Montage_" + Long.toString(time) + ".jpg");
// We assign the montage filename to the share button BEFORE we can click the button (otherwise the
// filename cannot be taken into account)
findValidateMontageShareButton3(f).setImageToShare(
montage.getMontageFullPath(), "image/jpeg");
Then in the onAction method related to the share button the code reads :
// Save the image with the ImageIO class
// We wait until the file is completely written to continue
Display.getInstance().invokeAndBlock(new Runnable() {
#Override
public void run() {
try (OutputStream os = FileSystemStorage.getInstance().openOutputStream(montage.getMontageFullPath())){
ImageIO.getImageIO().save(montage.getMontageImage(), os, ImageIO.FORMAT_JPEG, 1);
} catch (IOException e) {
Dialog.show("Erreur", "Impossible de sauvegarder le montage! Merci de vérifier l'espace disque disponible.", null, "OK" );
}
}
});
I tested it and it worked on the simulator but not on the device. Either with a png or a jpeg file, the file cannot be attached to the SMS or email (Android error message "abnormal file, can't attached file").
However if I do it a second time, then the file can be attached. So now the image is not missing but it cannot be attached (the first time) which is still embarrassing.

Create a .csv file and then tell the printer to print the file

So I have a program where I am able to successfully create a .csv file with my data.
I now have to somehow print that file.
I looked up a lot of resources about printing in WPF but they are all so complex and I can't make head and tails of what the barebones printing statements are.
Is there a way for me to just tell the application to take a specific filepath and then print the contents of the file as it would be if I manually went and opened the .csv file and hit print?
Edit:
Alternatively, I have been told I could do this; take a screenshot of my screen (printscreen) and then tell the printer to print the image from clipboard. But this has to be all done when a button called 'Print' is pressed.
Update:
For my first query, what I'm doing now is opening the .csv file when I press the print button and then using excel's print function to get my printout and its working.
But I would like to have it work with what is seen directly in the application with the printscreen method.
You can use the "Verb" property of ProcessStartInfo with Process.Start to open and print the CSV file with the default program associated with CSV files. You need to set the "Verb" to "print".
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "C:\\myfile.csv";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.Verb = "print";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Sharepoint 2010 Upload file using Silverlight 4.0

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu
Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Silverlight file upload - file is in use by another process (Excel, Word)

all. I have a problem with uploading of the file in Silverlight application. Here is a code sample. In case when this file is opened in other application (excel or word for example) it fails to open it, otherwise it's working fine. I'm using OpenFileDialog to choose the file and pass it to this function.
private byte[] GetFileContent(FileInfo file)
{
var result = new byte[] {};
try
{
using (var fs = file.OpenRead())
{
result = new byte[file.Length];
fs.Read(result, 0, (int)file.Length);
}
}
catch (Exception e)
{
// File is in use
}
return result;
}
Is there any way i can access this file or should i just notify the user that the file is locked?
You should notify the user that the file is currently in use by another program. If another program has the file open with a lock that does allow a shared read there is no way to bypass this lock.

Resources