【问题标题】:Java or Coldfusion File operationJava 或 Coldfusion 文件操作
【发布时间】:2011-03-07 22:18:29
【问题描述】:

我正在使用 Coldfusion MX,我想动态创建 .htaccess 文件的一部分。

例如,我有一个零件的开始和结束看起来像

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

现在每次我在coldfusion中生成这个.htaccess内容时,我都想删除Start and End之间的内容 部分并在此处写入新内容。

Coldfusion 有可能吗?

谢谢

【问题讨论】:

    标签: java coldfusion


    【解决方案1】:

    假设文件.htaccess.template 是这样的:

    # BEFORE
    # --- Start Part1 ---#
    
    # --- End Part1 ---#
    # AFTER
    

    在同一目录中有一个 ColdFusion 脚本,比如 htaccess.cfm(名称无关紧要):

    <!--- 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)>
    

    这将在同一目录中生成一个文件.htaccess。我认为一个问题将是处理放置在.htaccess 上的任何文件系统锁,以防止删除/覆盖,我不确定在这种情况下您需要做什么。

    在本例中,.htaccess 将是:

    # 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
    

    【讨论】:

      【解决方案2】:
      1. 将文件读入带有&lt;cffile&gt;的变量中
      2. 使用 listToArray() 将 var 转换为数组,使用 endline chr's 作为分隔符
      3. 打开&lt;cfsavecontent&gt;
      4. 循环并输出数组,直到到达# --- Start Part1 ---#
      5. 添加您自己的内容
      6. 循环并跳过数组,直到到达# --- End Part1 ---#
      7. 循环并输出数组,直到到达终点
      8. 使用&lt;cffile&gt;将保存的内容写入新的.htaccess

      不幸的是,直到 CF8,我们才能在不耗尽内存的情况下逐行读取任意大的文件。见:http://coldfused.blogspot.com/2007/07/new-file-io-in-coldfusion-8.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-25
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多