2012-03-19 3 views
1

나는이 코드를 MDN File I/O 페이지에서 바로 복사했습니다. if 문을 추가하여 파일이 이미 존재하는지 확인하고 그럴 경우 대신 읽었습니다.로컬 컴퓨터의 파일 읽기/쓰기

 Components.utils.import("resource://gre/modules/NetUtil.jsm"); 
    Components.utils.import("resource://gre/modules/FileUtils.jsm"); 

    var file = Components.classes["@mozilla.org/file/directory_service;1"]. 
       getService(Components.interfaces.nsIProperties). 
       get("Desk", Components.interfaces.nsIFile); 
    file.append("test.txt"); 

    if (!file.exists()) { 
     this.user_id = Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001); 

     var ostream = FileUtils.openSafeFileOutputStream(file) 
     var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]. 
         createInstance(Components.interfaces.nsIScriptableUnicodeConverter); 
     converter.charset = "UTF-8"; 
     var istream = converter.convertToInputStream(this.user_id); 

     // The last argument (the callback) is optional. 
     NetUtil.asyncCopy(istream, ostream, function(status) { 
      if (!Components.isSuccessCode(status)) { 
       alert('Error '+ status); 
       return; 
      } 

      alert('File created'); 
     }); 
    } else 
    { 
     NetUtil.asyncFetch(file, function(inputStream, status) { 
      if (!Components.isSuccessCode(status)) { 
       alert('error '+ status); 
       return; 
      } 

      // The file data is contained within inputStream. 
      // You can read it into a string with 
      this.user_id = NetUtil.readInputStreamToString(inputStream, inputStream.available()); 
     }); 
     alert('File exists already, do not create');  
    } 

    alert(this.user_id); 

파일을 잘 생성하여 열어서 읽을 수 있습니다. 그러나 파일이 이미있는 경우에는 this.user_id .. 채우지 않습니다. 단지 null과 같습니다. 그래서 내 문제는 특히 파일을 읽는 것입니다. 코드가 완료된 것을 의미 NetUtil.asyncFetch()에서 콜백 데이터로 호출되는 어떤 시점에서, 다음합니다 (alert()this.user_idnull 것을 보여줍니다 호출 포함) - 코드 읽기

+0

파일의 내용이 올바른지 확인 했습니까? –

+0

@David - 당신이 무슨 뜻인지 안다면, 당신은'contentType'을 말하는 겁니까? – thefoyer

답변

2

파일은 비동기 적으로 작동합니다. 그 때까지 this.user_id 물론 설정되지 않습니다. alert(this.user_id)을 콜백 함수로 이동하면 올바른 값이 표시됩니다.

파일 시스템의 현재 상태에 따라 상당한 시간이 걸릴 수 있으므로 파일 I/O 작업을 비동기로 유지하는 것이 좋습니다. 그러나 파일 조작이 즉시 발생한다고 가정하지 않는 방식으로 코드를 구조화해야합니다.

+0

다시 한번 블라디미르 (내가 당신에게 돈을 지불해야하는 것 같은 느낌). 이것은 내가 많은 변화를 만들었고 그 결과에 행복하다. 감사. – thefoyer

관련 문제