Ensure parent directory when creating a new file

createNewFile throws an exception if the parent directory doesn't exist
This commit is contained in:
Martin Bektchiev
2016-04-05 17:16:18 +03:00
parent 77ef1367a0
commit dcdd0a6b9d
3 changed files with 16 additions and 4 deletions

View File

@@ -638,4 +638,14 @@ export function test_UnlockAfterWrite(done) {
return file.remove(); return file.remove();
}).then(() => done()) }).then(() => done())
.catch(done); .catch(done);
}
export function test_CreateParentOnNewFile(done) {
var documentsFolderName = fs.knownFolders.documents().path;
var tempFileName = fs.path.join(documentsFolderName, "folder1", "folder2", "Test_File_Create_Parent.txt");
var file = fs.File.fromPath(tempFileName);
file.writeText("Hello World!").then(() => {
return fs.knownFolders.documents().getFolder("folder1").remove();
}).then(() => done())
.catch(done);
} }

View File

@@ -327,6 +327,7 @@ export class FileSystemAccess {
if (isFolder) { if (isFolder) {
created = javaFile.mkdirs(); created = javaFile.mkdirs();
} else { } else {
javaFile.getParentFile().mkdirs();
created = javaFile.createNewFile(); created = javaFile.createNewFile();
} }

View File

@@ -52,11 +52,12 @@ export class FileSystemAccess {
var exists = fileManager.fileExistsAtPath(path); var exists = fileManager.fileExistsAtPath(path);
if (!exists) { if (!exists) {
if (!fileManager.createFileAtPathContentsAttributes(path, null, null)) { var parentPath = this.getParent(path, onError).path;
if (!fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(parentPath, true, null) ||
!fileManager.createFileAtPathContentsAttributes(path, null, null)) {
if (onError) { if (onError) {
onError(new Error("Failed to create folder at path '" + path + "'")); onError(new Error("Failed to create file at path '" + path + "'"));
} }
return undefined; return undefined;
} }
} }
@@ -406,4 +407,4 @@ export class FileSystemAccess {
var nsString = NSString.stringWithString(NSString.pathWithComponents(nsArray)); var nsString = NSString.stringWithString(NSString.pathWithComponents(nsArray));
return nsString.stringByStandardizingPath; return nsString.stringByStandardizingPath;
} }
} }