开发者

Java or Coldfusion File operation

I am using Coldfusion MX and I want to create parts of .htaccess file dynamically.

for example 开发者_如何学GoI have a Start And End of a part looks like

> # --- Start Part1 ---#
> 
> # --- End Part1 ---#

now every time I generate this .htaccess contents in coldfusion I want to delete the contents between Start and End parts and write the new contents here.

Is it possible in Coldfusion?

Thanks


Assume a file .htaccess.template as such:

# BEFORE
# --- Start Part1 ---#

# --- End Part1 ---#
# AFTER

In the same directory there's a ColdFusion script, say htaccess.cfm (name doesn't matter):

<!--- note double pound signs, necessary to escape in CF --->
<cfset start = "## --- Start Part1 ---##">
<cfset end = "## --- End Part1 ---##">

<cfsavecontent variable="replacement"><cfoutput>
I will appear between the start and end comments!
Replace me with what you want to appear in the .htaccess file.
</cfoutput></cfsavecontent>

<cfset template = fileRead(getDirectoryFromPath(getCurrentTemplatePath()) & "/.htaccess.template")>

<cfset startPos = find(start, template)>
<cfset endPos = find(end, template)>

<cfset before = left(template, startPos + len(start) - 1)>
<cfset after = right(template, len(template) - endPos + 1)>

<cfset content = "#before##replacement##after#">

<!--- <cfoutput><pre>#content#</pre></cfoutput> --->

<cfset path = getDirectoryFromPath(getCurrentTemplatePath()) & "/.htaccess">
<cfif fileExists(path)><cfset fileDelete(path)></cfif>
<cfset fileWrite(path, content)>

This will generate a file .htaccess in the same directory. I think the one issue will be dealing with any file system locks placed on .htaccess, preventing deletion / overwriting, where I'm unsure what you'd need to do in that situation.

In this example .htaccess will be:

# BEFORE
# --- Start Part1 ---#
I will appear between the start and end comments!
Replace me with what you want to appear in the .htaccess file.
# --- End Part1 ---#
# AFTER


  1. Read the file into a var with <cffile>
  2. turn the var into an array using listToArray(), using endline chr's as delimiter
  3. open a <cfsavecontent> block
  4. loop through and output the array until you reach # --- Start Part1 ---#
  5. add your own content
  6. loop through and skip the array until you reach # --- End Part1 ---#
  7. loop through and output the array until you reach the end
  8. write the saved content to a new .htaccess with <cffile>

Unfortunately, not until CF8 that we can use read an arbitrarily large file line-by-line without exhausting memory. See: http://coldfused.blogspot.com/2007/07/new-file-io-in-coldfusion-8.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜