Writing to a file inside tell statement

Ok, so I'm an AppleScript newbie.
Wanted to write a script to have some expose preferences saved to a file, and after banging my head against the table for three hours I kinda found where the "File some object wasn’t open" error was coming from. Pruned and adjusted the code to explain the above:
set theFile to (path to home folder as Unicode text) & "ExpSet"
try
set theHandle to open for access file theFile with write permission
write "First line" to theHandle
tell application "System Events"
write "Second line" to theHandle -- Here's where it dies
end tell
close access theHandle
on error errMsg number errNum
display dialog errMsg
close access theHandle
end try
The error line is just a dumb replacement for the original one, where I was doing the actual save; it needs to be inside that tell statement to be able to get the preferences that I want to save. Now, that seems to be the problem, looking at the Event Log output:
tell current application
path to home folder as Unicode text
"AQUIJADA:Users:teran:"
open for access file "AQUIJADA:Users:teran:ExpSet" with write permission
1019
write "First line" to 1019
end tell
tell application "System Events"
write "Second line" to 1019
end tell
tell current application
display dialog "System Events got an error: File some object wasn’t open."
{button returned:"OK"}
close access 1019
end tell
The first write works fine because it is before the tell "System Events" statement, but then the second one dies apparently because the write is directed to System Events and not the script itself as in the first case. Is that the way it should work? Am I missing something here or just utterly lost?
Thanks in advance!

When you open a file for access, it is related to the application - you haven't opened your file in System Events, so it gives you the "not open" error. Normally you should only use a tell statement for dealing with properties from that object, otherwise you run the risk of the object not knowing what you are talking about.
In your example, you can just move the write statement out of the System Events tell statement:
tell application "System Events"
      get "Second line" -- the System Events property
end tell
write the result to theHandle

Similar Messages

  • Problem in writing to the file

    I use this labview code to read and save some electrical measurement data from a set of instruments. I am having a problem that the code stops writing to the file after a while. It stops responding too. The only way to stop it then is to use the task manager and kill it. The code was written for an older version of labview but now I am using labview 9. Everything else seems updated but there's a section that uses Write characters to file vi and that may be causing the problem. I made a few futile attempts to change it. I would highly appreciate if someone takes a look at it and could tell me what's going wrong.
    Attachments:
    JANUS 2.2_4K Probe edit (2).vi ‏60 KB

    I will second aeastet's advice - please look into how state machines and producer/consumer loops work and use them.  Your program is very inefficient, but is very similar to what I would have written before I learned about state machines and producer/consumer loops.  Start with the LabVIEW help and go from there.  These forums and the National Instruments website can give you lots of help.
    Two things that will help you for this particular problem:
    At every loop iteration, you are opening the file, seeking to the end of it, appending data, then closing the file.  This is very slow and the code you use, as mentioned above, will not work if the file size exceeds 2GBytes.  I would recommend you open the file once, then use the write primitive to write to it until you finish, then close it.  You do not need the write character to file VI.  No seeking.  No repetitive opening and closing.  You can either open and close outside the loop, or use case structures and boolean flags (as you have done for other things) to open and close inside the loop.
    After you write to the file, if you choose to graph, you are reopening the file, reading the entire thing, and plotting this data.  This is another major slowdown that will only get worse as your file gets bigger.  You would be far better off caching the data in a shift register and plotting it on demand.  It would probably take less memory, as well.  You may want to read the tutorial Managing Large Data Sets in LabVIEW.
    One last tip.  You use Value properties to read and set the values of front panel controls.  Local variables are far faster (about three orders of magnitude).  However, do not make the mistake of using local variables for data storage.  Data is wires.  Local variables are a way to communicate to the front panel.  You seem to have this down, but a reminder to others reading this thread is in order.
    Let us know if you need more explanation or help.  Good luck!
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • How to sync writing to a file?

    Hi all,
    I'm implementing a simple line logger for my web applications.
    Basically, I have some class with a "write" method, that appends a line of text into a certain file.
    All of my web apps log into the same file (by design).
    How do I make sure writing to the file is synchronized?
    The web apps cannot share logger objects between them (not even singletons, correct?) so using the 'synchronized' qualifier for the 'write' method won't work because each web app has its own instance of the logger object.
    Also, FileLock won't work since all web apps "live" inside the same JVM (accoding to javadoc, FileLock is not suitable for syncing file-writes by different threads within the same JVM).
    I've looked up the forum for answers to these questions, but non of the threads on this topic provided any leads...
    Any ideas?

    hii...
    can sum1 plz tell me how to replace bytes in a file?
    i've used randomaccess to open the file....read is
    contents and write back to it at the desired
    locations using seek()...however at some position if
    i wish to read the data and replace it with new data
    at exactly the same location...how can i do it??
    bye.i had already mentioned my problem....actually i want to read a record from a file and then update it at the same location in the file...so i need to replace it(or delete the record and re-write the new info).

  • To open a Excel and Doc file inside the AIR application

    How to open a Excel and Doc file inside the AIR application.  I have opened the PDF file inside the AIR application.  But i got stuck in opening the Exce and Doc file.  Please help me in this issue.

    AIR does not support this inherently. However, you could write code to parse these file formats. For example, the following is an ActionScript 3.0 library for reading and writing Excel files:
    http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1375018

  • Error while writing to a file

    Hi,
    I am getting an error while writing to a file.Here is the sample code in which I am getting error.The STDERR is getting printed to console but the same is not getting written to a file.
    package Sample;
    import java.util.*;
    import java.io.*;
    public class MediocreExecJavac
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("perl ic_start");
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    FileWriter fw=new FileWriter("result.txt");
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    fw.write(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    fw.close();
    } catch (Throwable t)
    t.printStackTrace();
    }Below is the output -
    <ERROR>
    Can't open perl script "ic_start": No such file or directory
    java.lang.NullPointerException
    at java.io.Writer.write(Unknown Source)
    at Sample.MediocreExecJavac.main(MediocreExecJavac.java:21)
    Please tell where the program is going wrong.

    i think it is just the path of file that u r missing

  • Validating xml-files inside jar-files  for JWS

    I want to use xml-files inside a jar-file and want to validate them with dtd-files,
    located in the same jar-file. This does work, but only as long as the dtd-file is
    in the same directory as the xml-file.
    For example, I have no problem, with a DOC Type-statement like
    <!DOCTYPE questestinterop SYSTEM "ims_qtiv1p1.dtd" >
    With this statement, however, one needs an approprate dtd in every directory containing an XML-file of that type.
    If however i want to gather the necessary dtd's in a directory one (or more) levels above with a DOCTYPE-statement of the form
    <!DOCTYPE questestinterop SYSTEM "../ims_qtiv1p1.dtd" >
    I get error messages of the form
    java.io.FileNotFoundException: JAR entry Mikro/Marshall/BookQuestions/../ims_qtiv1p1.dtd not found in C:\Dokumente und Einstellungen\wreiss\Anwendungsdaten\Sun\Java\Deployment\javaws\cache\http\Dwiwi.upb.de\P80\DM~vwl08\DMOViSS\DMoviss_current\RMMikro.jar
         at org.apache.crimson.parser.Parser2.fatal(Unknown Source)
         at org.apache.crimson.parser.Parser2.externalParameterEntity(Unknown Source)
         at org.apache.crimson.parser.Parser2.maybeDoctypeDecl(Unknown Source)
         at org.apache.crimson.parser.Parser2.parseInternal(Unknown Source)
         at org.apache.crimson.parser.Parser2.parse(Unknown Source)
         at org.apache.crimson.parser.XMLReaderImpl.parse(Unknown Source)
         at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(Unknown Source)
         at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
         at oviss.competenceCenter.XMLExpert.setElements(XMLExpert.java:245)
    though the dtd-file is in the parent-directory (inside the jar) and the unpacked xml-file can be successfully validated.
    Why does this happen. How can one use a single dtd for multiple xml-files (of the same type) in different directories?.
    Thanks
    Winfried Reiss

    In reply to myself, replacing the HTMLBrowser constructor with this;
    public HTMLBrowser()
                  URL url;
                  try
                       // Construct the URL
                       url= this.getClass().getResource('/'+dir+'/'+startPage);
                       setPage(url);
                  catch (Exception e)
                  System.out.println( "Problem setting help homepage");
                 setEditable(false);
                 addHyperlinkListener(new LinkListener(this));
            }made it work. This is because seemingly you need '/' at the start of the resouce's path and '/' as the separator, regardless of platform.
    I hope this helps someone else.
    John

  • Confused about "files inside a JAR"

    I have a program that has a Properties file which I would like to "save" into the JAR file, so it is not outside the JAR.
    I know this can be done, because I've seen some Java programs that save their configuration between sessions, but not via a file inside its directory. This leads me to believe the file is maintained within the JAR itself, which would be REALLY handy and secure.
    Is this a correct assumption? If so, how would I do it? Here's a "test program" that we can play with, how would I save MyProperties' properties field into the MyProgram JAR?
    package SBX;
    import java.util.*;
    import java.io.*;
    public class MyProgram {
        // Instance Variables
        public MyProperties myProp = new MyProperties();
        public String stringOne = "Will this be loaded?";
        public String stringTwo = "How about this one?";
        // Main Method
        public static void main(String[] args) {
            new MyProgram();
        // Constructors
        public MyProgram() {
            if ((new File("properties.txt")).exists()) {
                myProp.updateProgram(this);
            System.out.println("1) " + stringOne);
            System.out.println("2) " + stringTwo);
            myProp.updateProgram(this);
            System.out.println("3) " + stringOne);
            System.out.println("4) " + stringTwo);
            myProp.updateProperties(this);
            // Now that we've "updated" stringOne & stringTwo and "updated" myProp and saved it,
            // we should be able to get the values "ONE" and "TWO" for print outs 1 & 2 when we next
            // run the program, instead of "Will this be loaded?" and "How about this one?", as we got during the first run.
            // However, the thing I need help with is saving the Properties to the JAR file so it's not accessable
            // outside of the JAR file. How can this be done?
    class MyProperties {
        // Instance Variables
        private Properties properties;
        // Constructors
        public MyProperties() {
            Properties defaults = new Properties();
            defaults.setProperty("stringOne", "ONE");
            defaults.setProperty("stringTwo", "TWO");
            properties = new Properties(defaults);
            try {
                FileInputStream fis = new FileInputStream("properties.txt");
                properties.load(fis);
                fis.close();
            catch (Exception e) {
                System.out.println("No properties file found, ignore this; one will be saved when the program exits.");
        // Methods
        public void updateProgram(MyProgram prg) {
            prg.stringOne = properties.getProperty("stringOne");
            prg.stringTwo = properties.getProperty("stringTwo");
        public void updateProperties(MyProgram prg) {
            properties.setProperty("stringOne", prg.stringOne);
            properties.setProperty("stringTwo", prg.stringTwo);
            try {
                FileOutputStream fos = new FileOutputStream("properties.txt");
                properties.store(fos, "A header");
                fos.close();
            catch (Exception e) {
                e.printStackTrace();
    }Thanks for any help!
    PS...writing demo programs is kind of fun :)

    Fossie,
    Yup... you can jar up your properties file... you just need to add it to manifest file and jar (the program) takes care of the rest... google that there's loads of existing articles.
    BUT, I don't think you can modify the properties file in the jar... it may be possible, but I just don't know how. Instead (I think) you ship your default properties file in the jar, but still save a local properties file to the same directory as the jar (obviously won't work for applets)... then you load your defaults, and the local settings over the top.
    and PS I don't see how sticking a properties file in the jar would "secure" it in any fashion... it's just a zip file after all... would you care to elaborate?
    Cheers,
    Keith.

  • Error writing the project file. Error loading type library / dll

    Hi all,
    I am trying to create a new portal project in PDK.NET. But I am getting this error- "Error writing the project file. Error loading type library / dll". Can anyone tell me how to solve this error.
    rgds

    I get this same error.  Was working fine until I installed the SAP .Net Connector 2.0.  Now it does not work even after it was uninstalled.  Please help.

  • Change comma with dot in writing measuremen​t file

    Hello,
    I'm using the write to measurement file vi for save some data. I don't manage to read the text file in Matlab, I guess is because the decimal separator is the comma.
    Is there a simple way in LabVIEW for set the decimal separator to be the dot instead of the comma? (in the writing to measurement file vi)
    now the data is like this 56,897 but I would like it in the format 56.897
    Thanks
    Solved!
    Go to Solution.

    It has been working fine inside LabVIEW, but when I make the .exe application and start recording it register the text file with the comma separator again. So I guess it was just a temporary setting of LabVIEW.
    Is there a way to have the dot separator also when I register the data file from the application .exe?
    I don't find a way to set it in the "Write to measurement file"..
    Regards

  • Problem writing to a file on a shared drive

    I am having problems with my application not writing to a file on a shared drive. Actually it works perfect on one computer, but not on any other computer. Any ideas on why this would not work. Here is my code below, I think this may be an issue with permissions on the shared drive but have played with those until I am sick of it and nothing works. Any help on getting it to write to a file on a shared drive would be great.
    report2 = new JButton("Provider Order Entry");
                        report2.addActionListener(new ActionListener() {
                             public void actionPerformed (ActionEvent e) {
                                  if (e.getSource() == report2) {
                                       try {
                                            File file = new File("z:\\Provider Order Entry Reports\\ACCESSFILE.RMD");
                                            FileReader checkAccess = new FileReader(file);
                                            BufferedReader checkAccessBuff = new BufferedReader(checkAccess);
                                            boolean eof = false;
                                            while (!eof) {
                                                 String line = checkAccessBuff.readLine();
                                                 if (line != null) {
                                                      eof = true;
                                                      checkAccess.close();
                                                      checkAccessBuff.close();
                                                      if (!poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setSize(575, 200);
                                                           poeSelectionWindow.setBackground(blue);
                                                           JFrame.setDefaultLookAndFeelDecorated(false);
                                                           poeSelectionWindow.setVisible(true);
                                                      else if (poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setVisible(false);
                                       catch (IOException error) {
                                            Component controllingFrame = null;
                                            JOptionPane.showMessageDialog(controllingFrame,
                                                       "YOU DO NOT HAVE ACCESS TO THIS OPTION" + "\n" +
                                                       "PLEASE CONTACT IRM SUPPORT TO REQUEST ACCESS ",
                                                       "ACCESS DENIED",
                                                       JOptionPane.ERROR_MESSAGE);
                                            try {
                                                 File errorFile = new File("Z:\\LOG\\LOGGER.log");
                                                 String username = System.getProperty("user.name");
                                                 InetAddress addr = InetAddress.getLocalHost();
                                                 Date date = new Date();
                                                 BufferedWriter bw = new BufferedWriter(new FileWriter(errorFile, true));
                                               bw.write("ACCESS ATTEMPTED ON: Provider Order Entry Report BY:" + username + " At Workstation/IP: "
                                                         + addr + " " + date);
                                               bw.newLine();
                                               bw.flush();
                                               bw.close();
                                            catch (IOException error1) {
                                                 System.out.println("Error-- " + error1.toString());
                                            catch (NullPointerException NPE) {
                                                 System.out.println("Error -- " + NPE.toString());                                                       
                                       catch (NullPointerException NPE) {
                                            System.out.println("Error -- " + NPE.toString());                                                       
                        });

    So how do I stop the
    NPE from occurring.By not dereferencing a null reference.
    Thingamabob xyz = doSomethingWhichMightReturnNull();
    if (xyz != null)
    // go ahead and use xyz here
    If you leave out the above "if" statement check, and just willy-nilly try to use xyz when it is null, you'll get the NPE.
    It is occurring on the file
    name. I have never been able to stop the file name
    from throwing a NPE.I don't know how that translates to some lines of your code.

  • Please help with "Error writing the project file. The specified module could not be found." error.

    I am a student.  I've been trying to install and use Visual Studio 2013 Professional for three weeks now and I cannot get it to work.  I am now two weeks behind in my Visual Basic class.  I've installed, uninstalled, ran the repair option... 
    I've tried everything I know how to do.  I just spent 45 minutes on the phone with Microsoft, was transferred four times and finally told I will have to use the forums to find an answer.  I'm almost completely out of patience with this.
    I got the software through the Dream Spark program as a student.  I installed it with the web installer and it appeared to install fine.  When I try to create a new project, I get the error:  "Error writing the project file.  The
    specified module could not be found."
    When I exit the application, I also get:  "The automatically saved settings file 'c:\users\user\documents\visual studio 2013\Settings\CurrentSettings-2015-02-02.vssettings' is not available for write.  You can change this file on the 'Import
    and Export Settings' Tools Options page."
    Please tell me you can help.

    Hi,
    could you please try the points mentioned here:
    http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/0376db8f-4761-4ae5-9af2-98c53216318a#VS_IDE_unexpected_problems to eliminate the possible cause of your issue?
    Please update the result in the forum after you try the method above!
    Best Wishes!
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click <a
    href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

  • Updating files inside App Bundle

    This is dealing with an app bundles in the normal desktop environment.
    I have a bundle I've created that has already been distributed. We've updated the code in the Jar file some and want to push this new Jar out to the existing bundles. There are user created files inside the existing bundles that should not be lost so simply creating a new bundle to replace the old isn't an option. Is there a recommended way to accomplish what I'm trying to do?

    KenW2 wrote:
    Am I getting trolled by lazarus because I made a n00b mistake and he's a jerk, or did I deserve that helpful reply because I'm stoopid?
    Neither of the above, Ken. Consider it an honor to have successfully invoked that visit. Q Lazarus has a mission here that few or none of us understand. Yet I know his work is not done.
    If some context would help, refer to the list of aliases provided by KT, and try to appreciate the author's unique style. I don't think it's overstatement to say that some of these contributions have elevated rudeness and abuse into an art form. In time--I got over my first helpful reply(TM) in just two short weeks--you may recognize the work of an authentic American crank, possibly one of the last of his kind. If you haven't done so already, try to see Clint Eastwood's +Gran Torino+. This is how I often imagine my hero--though Walt Kowalski had a front lawn to protect, and I don't think I know anyone in San Franscicso who owns a front lawn.
    That said, I must tell you that the programmer channeling Walt is an expert in most of the topics which earn his comments. Would you rather see a surgeon with a pleasant, supportive bedside manner, or one who knows what he's doing? His advice is almost always good, and on the days he remembers his meds, you'll find solid answers to the most difficult questions in the forum.
    Welcome to the Dev. Forum, Ken! I hope you'll be back whenever you can use some help, and whenever you can help someone else here.
    \- Ray

  • Is .class file contains comment statement

    Hi,
    Is .class file contains comment statement , ( ie )which i gave in comment line in my .java file.
    Thanks in advance.
    Regards,
    kumar

    I don't have a file Is.class so I can't tell, but indeed if the Java compiler created the file from some source it won't contain any comments that existed in that source.

  • Should Spotlight be indexing non-image files inside my iPhoto '11 Library?

    The title says all. I've noticed that certain Spotlight searches sometimes turn up obscure files inside file bundles, such as inside my iPhoto library:
    This doesn't seem normal. How can it be fixed?

    That is generally true: when I want to find something that I know to be inside an application bundle I use EasyFind (and even with that it is necessary to explicitly tell it to look inside bundles). But I just checked using the search for phrase of "PhotoFaces" which is a sub-sub-folder and collection of files inside the iPhoto Library, and Spotlight found it with no problem whatsoever. I presume that whatever magic the programmers did to allow Spotlight's indexer to get photo files just works for everything in the iPhoto Library.
    Francine
    Francine
    Schwieder

  • Writing binary .raw file

    Hi 
    I am facing problem with writing binary file as .raw file. I have attached my VI please let me know whether I am mistaking with creating and writing files. I will appreciate your help. 
    Thanks 
    Attachments:
    writing_binary file.vi ‏67 KB

    Your actual writing of the file looks fine to me.  If you wanted to make it a little simpler, you could actually not use the File Open and the File Close functions.  You can wire the path straight into the Write Binary File and if you don't wire the file reference out, it will close the file.  Were you having problems with something?
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

Maybe you are looking for

  • Execute unix command in abap code

    Hi, I have a request to execute a script command in a remote unix server, should i use 'call function ...destination'? Thanks. Legend.

  • Hyperion Planning 11.1.1.3: Add New User

    1:      When trying to refresh security filters using the workspace interface I get the following error(s) AND the essbase security file gets messed up (including, the native admin id). I then need to login with an alternate id that does not have acc

  • Removing admin password form Access 2003 database front end and back end

    We have a legacy database that has been passed down from the original creator, who is no longer with the organization. It was created in Access 2003. It has a front end and a back end. The original admin password can not be located and we are in the

  • Filters Section is not visible in Mobile App???

    I added few filters in my report in Power BI Preview Web but its not visible in Mobile App. Anybody has any idea?? Atul, 

  • Why does ad blocker not work?

    this will be complicated.... my anti virus software, avast also notifies users that software is not up to date. when i updated that software i also got unwanted sh*t without my knowledge. those items include my PC back up and arcadeplayer. arcade pla