Tải bản đầy đủ - 0 (trang)
Hack 80. Open Files, Directories, and URLs on Mac OS X

Hack 80. Open Files, Directories, and URLs on Mac OS X

Tải bản đầy đủ - 0trang





}



Thisprogramwillopenafileinthecurrentdirectory(notes.txt),

inthedefaultviewerfortextfiles,usuallyTextEdit.Youcanalso

specifyanabsolutepathforthefile:





rt.exec("open/Users/josh/Desktop/notes.txt");



Ifyoupassadirectoryinsteadofafile,thenOSXwillopenthat

directoryinanewFinderwindow.Thiscanbeusefulfor

showingthelocationofarecentlydownloadedfileor

demonstratingwheretoinstallnewsoftware:











//openthecurrentworkingdirectory

rt.exec("open.");

//opentheapplicationsdirectory

rt.exec("open/Applications");



Finally,youcanopenanywebpageusingtheuser'sdefaultweb

browser(probablySafari)bycallingopenwithaURL:







//openYahoo!intheuser'swebbrowser

rt.exec("openhttp://www.yahoo.com/");



11.3.2.HandleSpaces

Somefilepathsmaycontainspaces.Whenyourunopenfromthe

commandlineyoucanescapethesespacesusingquoteslike



this:





open'CurrentNotes.txt'



Unfortunately,quoteswon'tworkwhenyoucallopenfroma

programbecausethequotesareactuallyinterpretedbythe

user'scommand-lineshell,notopenitself.Whenyoucallopen

directlyfromaprogram,youarebypassingtheshellandlose

quoteinterpolation.Thesolutionistobreakthecommandline

intoanarrayofargumentsmanually.Thatwayopenknowswhat

isaspaceandwhatisthegapbetweenarguments:









Runtimert=Runtime.getRuntime();

String[]cmd={"open","CurrentNotes.txt"};

rt.exec(cmd);



Now,youmightwonderwhyopenneedstodistinguishbetween

argumentgapsandrealspaceswhenittakesonlyone

argumenttobeginwith.openactuallydoeshavesomeother

arguments.Forexample,-twillforcethefiletobeopenedin

TextEdit,and-fwillmakeopenreadfromstandardinputrather

thanafile.

Themostusefulextraargumentisprobably-a,whichletsyou

forcethefiletobeopenedinaparticularprogramratherthan

justusingthedefault.Forexample,ifyouwantedtoopena

textfileinMicrosoftWordinsteadofthedefaulttexteditor,you

coulddosomethinglikethis:













publicstaticvoidmain(String[]args)throwsException



Runtimert=Runtime.getRuntime();



String[]cmd={



"open",



"-a",

















"MicrosoftWord",



"mynotes.txt"

};

rt.exec(cmd);

}



Noticeyouhavetouseanarrayinsteadofasinglestringbecause

MicrosoftWordhasaspaceinit.Ifyoudon'tdothat,theprogramwill

failwithabuserror.



openisasimplebutverypowerfulprogrambecauseitgivesyou



easyaccesstolaunchingprogramsandfileswithoutknowing

theuser'ssettings.Thedefaultapplicationswillbeusedfor

eachfiletype,includingURLs.Youdon'thavetohardcodethis

informationintoyourprogram,thuscreatingabetter

experienceforyouruser.



Tolearnmoreabouttheopencommand,youcantypemanopenintoa

terminalwindow.



Hack81.MakeMacApplicationsBehave

Normally



Settingafewsystempropertieswillmakeyour

applicationseemmorelikeotherMacapps.

Ofthedesktopplatformsyourapplicationislikelytorunon,the

Macistheleastliketheothers.Maybeit'sbecausethevarious

LinuxdesktopshemmedcloselytoWindows'waysofthinking,

ormaybetheGNOMEguyshadneverusedaMacanddidn't

"thinkdifferent."Buttheresultisthatcertainassumptionsyou

mightreasonablymakeonWindowsorLinuxlikeassumingthat

windowshavemenubarsandthatanycorneroredgeofa

windowcanbedraggedtoresizethewindowaren'tcorrecton

theMac.

Tosmoothoverthecross-platformdifferencessomewhat,Apple

doescertainthingsdifferentlyinitsJavaimplementation.For

onething,itwillautomaticallyputaSwingapplicationintoits

nativeLookandFeel,Aqua,ratherthandefaultingintocrossplatformMetalorOceanaswouldhappenonotherplatforms.In

otherwords,youdon'thavetodoanythingspecialtopickup

theMacLookandFeel,althoughredundantlyaskingforand

settingthenativeLookandFeelclassnamedoesn'thurteither.

Moreover,Appleprovidessomekey/valuepairsthatyoucanset

intheJavasystempropertiestogetevenmoreMac-like

behavior.Becausethesepropertiesallstartwithappleor

com.apple,youcansetthemandnotworrythatthey'llaffectthe

behaviorofyourapplicationonanyotherplatform.



11.4.1.UsingtheAppleSystemProperties



Applehasbeenchangingthenamesandbehaviorsofthese

systempropertiesforawhile,andsomeofthemaredeprecated

orno-op'ed,soI'lljustshowfourofthemostusefuloneshere.

Toseethewholelist,checkouttheRuntimeSystemProperties

ofApple'sJava1.4.1releasenoteson

http://developer.apple.com/releasenotes/Java/index.html.

Youcansetthepropertiesseveralways.Theobviouswayisto

usethe-Dcommand-lineargument:





java-Dapple.awt.showGrowBox=trueMyClass



However,thisbecomestedioustotypeafteryoudecidetouse

multipleproperties.Anotheroptionistosimplycall

System.setProperty()inyourcode,thoughyou'llneedtodosoas

soonaspossiblesothedesiredpropertygetspickedupbythe

JVMbeforeit'sneeded.Athirdoptionexistsaswell:ifyou're

bundlingtheJavaapplicationasadouble-clickableMac

application,yourtoolofchoicewillgiveyouanopportunityto

setthesevalues.Forexample,theJarBundlerthatApple

provideswithitsdevelopertoolshasapropertiespaneinwhich

youcanentername/valuepairs;thesearesavedwiththe

applicationbundleandprovidedtotheJVMasifthey'dbeenset

onthecommandline.



Thedownloadablebookcodecontainsdemoapplicationsforallthe

tricksshowninthischapter,butsincethepointinthishackistheonelineSystem.setProperty()callandnot20linesofcodethatdemonstrate

theeffect,thedemocodeisnotshownhere,justscreenshotsofthe

results.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 80. Open Files, Directories, and URLs on Mac OS X

Tải bản đầy đủ ngay(0 tr)

×