Skip to main content
Participating Frequently
May 22, 2013
Question

Can load text file in Windows - not on the Mac?

  • May 22, 2013
  • 2 replies
  • 550 views

I have some code that loads a text file into an array that works fine in windows, but fails on the Mac  I'm sure it's a path issue but I've spent several hours trying to work this out.

Windows code works fine:

    var textPath =  "c:\\temp\\textfile.txt";

     try {

        var myFile = File(textPath);

        var mymenuItems=[];

        var menuItems=[];

        myFile.open('r');

        while(!myFile.eof){

            mymenuItems.push(myFile.readln());

        }

        myFile.close();

Mac Code Fails

  var textPath = '/User/wizbowes/Desktop/text.txt';

     try {

        var myFile = new File(textPath);  //tried both with and without new - same effect

        var mymenuItems=[];

        var menuItems=[];

       myFile.open('r');

   while(!myFile.eof){

            mymenuItems.push(myFile.readln());

          }

When debugging on the mac myFile.eof shows true straight after I open the file and therefore never enters the loop to populate the array

What on earth am I doing wrong?

This topic has been closed for replies.

2 replies

Inspiring
May 23, 2013

Your snippet is incomplete… You must be debugging with more? Anyhows this is just fine here on a mac…

#target bridge

var textPath = File( Folder.desktop + '/text.txt' );

var myFile = File( textPath );

var mymenuItems = [];

var menuItems = [];

if ( textPath.exists ) {

    try{

        myFile.open( 'r' );

        while( !myFile.eof ) {

            mymenuItems.push( myFile.readln() );

        };

    }catch(e){}

    $.writeln( mymenuItems );

}else{ alert( 'File not found' ) };

Inspiring
May 23, 2013

1. For files on your desktop you can use a shortcut.

var textPath = '~/Desktop/text.txt';

2. Make sure the file object is valid before you open for reading. The new keyword is not really needed it just make clear in the code that you are creating a new file object. However just creating a file object does not means that the file already exists. You could have an invalid path.

try {
        var myFile = new File(textPath);

        if(myFile.exists){

           // rest of the code

        }

3. If you don't want to check that the file exists you could check the return of the file.open() method. It should return true if it opened the file when opening an existing file.

var openSuccess = myFile.open('r');

if(openSuccess){

    // some code that reads from the file here

}