Like the title says I want to create a folder in a specific directory with Adobe Air.
If I use static methods of File like File.userDirectory works fine but I need to give the choice to select the directory.
I am trying this:
file.addEventListener(Event.SELECT, dirSelected);
file.browseForDirectory("Select a directory");
function dirSelected(e:Event):void {
trace(file.nativePath);
file.resolvePath("new_folder");
file.createDirectory();
}
Nothing happens
"resolvePath: Creates a new File object with a path relative to this File object's path, based on the path parameter (a string)."
So:
var newDir:File = file.resolvePath("new_folder");
newDir.createDirectory();
Related
I need to read a text file with readLines() and I've already found this question, but the code in the answers always uses some variation of javaClass; it seems to work only inside a class, while I'm using just a simple Kotlin file with no declared classes. Writing it like this is correct syntax-wise but it looks really ugly and it always returns null, so it must be wrong:
val lines = object {}.javaClass.getResource("file.txt")?.toURI()?.toPath()?.readLines()
Of course I could just specify the raw path like this, but I wonder if there's a better way:
val lines = File("src/main/resources/file.txt").readLines()
Thanks to this answer for providing the correct way to read the file. Currently, reading files from resources without using javaClass or similar constructs doesn't seem to be possible.
// use this if you're inside a class
val lines = this::class.java.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
// use this otherwise
val lines = object {}.javaClass.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
According to other similar questions I've found, the second way might also work within a lambda but I haven't tested it. Notice the need for the ?. operator and the lines?.let {} syntax needed from this point onward, because getResourceAsStream() returns null if no resource is found with the given name.
Kotlin doesn't have its own means of getting a resource, so you have to use Java's method Class.getResource. You should not assume that the resource is a file (i.e. don't use toPath) as it could well be an entry in a jar, and not a file on the file system. To read a resource, it is easier to get the resource as an InputStream and then read lines from it:
val lines = this::class.java.getResourceAsStream("file.txt").bufferedReader().readLines()
I'm not sure if my response attempts to answer your exact question, but perhaps you could do something like this:
I'm guessing in the final use case, the file names would be dynamic - Not statically declared. In which case, if you have access to or know the path to the folder, you could do something like this:
// Create an extension function on the String class to retrieve a list of
// files available within a folder. Though I have not added a check here
// to validate this, a condition can be added to assert if the extension
// called is executed on a folder or not
fun String.getFilesInFolder(): Array<out File>? = with(File(this)) { return listFiles() }
// Call the extension function on the String folder path wherever required
fun retrieveFiles(): Array<out File>? = [PATH TO FOLDER].getFilesInFolder()
Once you have a reference to the List<out File> object, you could do something like this:
// Create an extension function to read
fun File.retrieveContent() = readLines()
// You can can further expand this use case to conditionally return
// readLines() or entire file data using a buffered reader or convert file
// content to a Data class through GSON/whatever.
// You can use Generic Constraints
// Refer this article for possibilities
// https://kotlinlang.org/docs/generics.html#generic-constraints
// Then simply call this extension function after retrieving files in the folder.
listOfFiles?.forEach { singleFile -> println(singleFile.retrieveContent()) }
In order to have the same url that work for both Jar or in local, the url (or path) needs to be a relative path from the repository root.
..meaning, the location of your file or folder from your src folder.
could be "/main/resources/your-folder/" or "/client/notes/somefile.md"
The url must be a relative path from the repository root.
it must be "src/main/resources/your-folder/" or "src/client/notes/somefile.md"
Now you get the drill, and luckily for Intellij Idea users, you can get the correct path with a right-click on the folder or file -> copy Path/Reference.. -> Path From Repository Root (this is it)
Last, paste it and do your thing.
I'm rather new to Google Scripts. We are wanting to make all files uploaded to a single folder in Google Drive be automatically moved to other folders, based on part of their file name.
3 example files: APX PMT 05.02.2019, ALT PMT 05.03.2019, BEA PMT 05.04.2019
We want these files to be moved to their destination folders based on the first 3 letters of their file name. APX PMT 05.02.2019 gets moved to the APX folder, ALT PMT 05.03.2019 gets moved to the ALT folder, ect.
Do not have code samples as I'm extremely new to this. Move files automatically from one folder to another in Google Drive is a good start on me learning this, but still unsure how to make it move file based on only part of the file name.
Results: Wanting people to be able to upload files to a single destination, and the code auto moves them to their proper folders.
Test Code version 2.0 . Works as below if I remove the spaces between the 2 character sets (change BEA RFT to BEARFT or BEA_RFT) , as our workplace would like them sorted by the first 7 characters in the file name now. How can i make it work when there is a space in the characters?:
function moveFiles() {
var dfldrs=['BEA RFT', 'BEA ADJ', 'BEA PMT', 'BEA CHG'];//Seven letter prefixes
var ofObj={BEA RFT:'ID',BEA ADJ:'ID',BEA PMT:'ID',BEA CHG:'ID'};//distribution folder ids
var upldFldr=DriveApp.getFolderById('ID');
var files=upldFldr.getFiles();
while(files.hasNext()) {
var file=files.next();
var key=file.getName().slice(0,7);
var index=dfldrs.indexOf(key);
if(index>-1) {
Drive.Files.update({"parents": [{'id': ofObj[key]}]}, file.getId());
}
}
}
Moving Files
Please, Read these instructions before running script
You need to provide the three letter prefixes
You need to provide the distribution folder ids associated with each prefix
You need to provide the upload folder id
You need to run this program from your upload file script or provide an alternate trigger function as you desire.
You need to enable Advance Drive API version 2
The Code
function moveFiles() {
var dfldrs=['APX','ALT','BEA'];//Three letter prefixes
var ofObj={APX:'APX id',ALT:'ALT id',BEA:'BEA id'};//distribution folder ids
var upldFldr=DriveApp.getFolderById('folderid');
var files=upldFldr.getFiles();
while(files.hasNext()) {
var file=files.next();
var key=file.getName().slice(0,3);
var index=dfldrs.indexOf(key);
if(index>-1) {
Drive.Files.update({"parents": [{"id": ofObj[key]}]}, file.getId());
}
}
}
Drive API Reference
I'm using the features of Java 7 to read in a file. For that purpose I need an object of type Path. In my code, I use the getResource() function to get the relative path (of type URL) to a file.
However, now I have the problem that I don't really now how to get from an object of type URL to an object of type Path easily (without having to go through castings to e.g. to URI then to File and from that to Path)?
Here an example to show you what I would like to do:
URL url = getClass().getResource("file.txt");
Path path = (new File(url.toURI())).toPath(); //is there an easier way?
List<String> list = Files.readAllLines(path, Charset.defaultCharset());
So is there an easier way to achieve that and not having to do that code mess on line 2?
How about
Path path = Paths.get(url.toURI());
It is not proper to create a File from your URL, since it's gotten from the classpath and the file may actually be within a jar.
In Scala would be
import java.nio.file.Paths
val resource = getClass.getResource("myfile.txt")
val path = Paths.get(resource.toURI)
In Java should be the same (with slightly different syntax)
I have a directory that contains a list of files. I wanted to get the latest file out of all the contents of the said directory. How will I do that?
I am using this code, but I am not getting the latest file out of it. Please help.
def fileDir = new File("A/B").listFiles().first()
Thanks.
As simple as:
new File( 'A/B' ).listFiles()?.sort { -it.lastModified() }?.head()
(taking the negative lastModified, as we want the newest file first)
The following code works fine when returning a file on a mac since it automatically appends the
file extension to the name of the file.
On windows however i have to type in the extension of the file as part of the file name in order for it to return with that extension....even though the extension is selected in the 'save type as' pulldown menu.
is there a way to automatically append the extension to the name when returning a file from the filechooser on windows?
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(fileExtension.toUpperCase()+" files(*."+fileExtension+")", "*."+fileExtension);
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
final File file = fileChooser.showSaveDialog(MyStage.this);
I ran into the same issue. My solution was to make a new File, and append the file extension as a string in the File constructor.
If you want users to be able to select and overwrite an existing file, make sure and add a check to make sure the initial save file does not contain the particular extension already before appending or else you will get something like "test.xls.xls".
FileChooser fc = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XLS File (*.xls)", "*.xls");
fc.getExtensionFilters().add(extFilter);
File save = fc.showSaveDialog(stage);
save = new File(save.getAbsolutePath()+".xls");
FileOutputStream fileOut = new FileOutputStream(save);