Having problems with my code, So I am currently trying to create a new directory and also store a text file within that folder I have created, I looked at a couple of examples but it seems like they only focus on a specific thing like how to create a file or a folder but never how to utilise both. How can I achieve this? I keep hitting exception errors when I try doing different methods, thanks!
val newFile : Int = 1
val fileString = "nameData"
//so we are creating variable to store the directory information
val folderDir = File("G:\\Random Projects\\JVM\\database\\Collection 1")
//we use that variable to create a File class which will create a folder called nameData
//this will also be stored in another variable called f
val f = File(folderDir, "nameData")
//this will create the actual folder based on the variable information
f.mkdir()
//creating file
try {
val fo = FileWriter(fileString, true)
fo.write(a)
fo.close()
} catch (ex:Exception) {
println("Something Went Wrong When Creating File!!")
}
The problem is that you probably don't have the whole folder structure created, that's why you usually use the mkdirs (note the s at the end) function. You can then use the writeBytes function to write the content:
val fileString = "nameData"
val folderDir = File("myfolder")
val f = File(folderDir, "nameData")
f.parentFile.mkdirs()
f.writeBytes(fileString.toByteArray())
Related
In a completely fresh project, I want to create a single file myFile.json inside the src/main/resources/ folder at run time.
For reading a file, I need to do some config in the build.gradle.kts file, but I can't find anything on what to do for creating a file.
Assuming the directory src/main/resources/ exists:
val f = File("src/main/resources/myFile.json")
withContext(Dispatchers.IO) {
f.createNewFile() // This is the answer to the question
f.printWriter().use { out ->
out.println("{}")
}
}
#Endzeit has asked what have you tried so far. Please share the code.
Like #cyberbrain says - are you sure you want to write to resources folder?
Here is code that writes back to where the source resources folder is:
fun main(args: Array<String>) {
// Let's assume you want your project to be portable, so you don't
// want to use absolute file paths.
// Find out where your IDE will launch the project from. Normally this is
// the root folder of the whole project. Find out with this: the `canonicalPath` will help:
val workingFolder = File(".")
println("workingFolder=${workingFolder.canonicalPath}")
// Define the folder you want to write in to
// this will vary especially if you have a nested project structure
// IntelliJ under the Edit > Copy Path menu option will help you find the resources
// relative location
val parentFolder = File("src/main/resources")
println("parentFolder=${parentFolder.canonicalPath}")
require(parentFolder.exists())
val outFile = File(parentFolder, "test.txt")
outFile.printWriter(StandardCharsets.UTF_8).use {
it.println("Hello world")
}
println("Wrote to ${outFile.canonicalPath}")
}
I'm a beginner developer just starting with HMS. I'm trying to write a code that finds the "profile.json" file, which was previously uploaded to the cloud into the folder "DebtSorter". My code (Kotlin) for it currently looks like:
var fileList: MutableList<File?> = mutableListOf()
thread {
try {
val drive = buildDrive()
val request = drive.files().list()
var cursor: String?
fileList = ArrayList()
do {
var result = request.setQueryParam("fileName contains 'profile'")
.setOrderBy("fileName")
.setPageSize(10)
.setFields("*")
.execute()
for (file in result.files) {
fileList.add(file)
}
cursor = result.nextCursor
request.cursor = cursor
} while (!StringUtils.isNullOrEmpty(cursor))
} catch (e: java.lang.Exception) {
Toast.makeText(applicationContext, "executeFilesList exception: $e", Toast.LENGTH_LONG)
.show()
}
}
return fileList
However, the returned fileList is always empty, even when I upload the file to the root of the cloud. I think I'm messing something up with the query string, because I can upload files just fine. Can someone tell me the syntax and keywords used in the query string, and possibly help me with the code and how to search in a given folder in HMS Drive kit?
Update:
You can also refer to the demo: https://github.com/HMS-Core/hms-drive-serverdemo In the demo, the thread executes the method of obtaining the file list directly.
Your query parameters is incorrect. You can't define the format of your query string. Please refer to this sample query statement.
(assuming that the ID of folder A is f192358798744098816):
To query all files in folder A, run the following statement: 'f192358798744098816' in parentFolder and mimeType != 'application/vnd.huawei-apps.folder'
To query all folders in the recycle bin, run the following statement: mimeType='application/vnd.huawei-apps.folder' and recycled=true
The query criteria 'fileId' in parentFolder and recycled=true cannot be used together, that is, a user cannot query files or folders in a specified parent folder in the recycle bin.
For more details, see the official guide.
In the end, the problem was with creating the thread. Since the thread is asynchronous and I created the fileList variable before the thread, modified it in the thread and returned it after the thread, the actual modification happened after the method already returned with the empty fileList. I took out the lines with thread and put the method call into a thread. This solved it.
I have a file, where the variables are "static" in java sense, and I want to access them by the file name. I am giving an example.
private var user:User?= null// this is put directly inside the file
fun saveMe(user: User?){
saveObject(user, USER_FILE)
FileStorage.user = user// this method is not allowed. How to access the top level user variable from here?
}
I don't know if this has been asked before, I guess the question is clear, about accessing the top level variable from a function that has same name argument. I don't want to rename either of the variables.
Option 1: Wrap your file into object:
object FileStorage {
// all your previous file content
}
Then FileStorage.user means exactly what you want.
Option 2 (if your file has a package declaration):
fun saveMe(user: User?){
saveObject(user, USER_FILE)
your.package.user = user
}
Option 3: add indirection:
private var user:User?= null
fun setTopLeverUser(_user: User?) { user = _user; }
fun saveMe(user: User?){
saveObject(user, USER_FILE)
setTopLevelUser(user)
}
The following code is great for renaming a file if you know the file is in applicationStorageDirectory
var sourceFile:File = File.applicationStorageDirectory;
sourceFile = sourceFile.resolvePath("Kalimba.snd");
var destination:File = File.applicationStorageDirectory;
destination = destination.resolvePath("test.snd");
try
{
sourceFile.moveTo(destination, true);
}
catch (error:Error)
{
trace("Error:" + error.message);
}
How do you set the sourceFile if all you have is the file's native path in a string? Like this:
D:\Software\files\testList.db
This throws errors:
sourceFile = sourceFile.resolvePath("D:\Software\files\testList.db");
The idea is I want to rename a file I had previously loaded into a var. I figured I'd extract the native path to a String var, null the File var (so the OS doesn't tell me it can't be renamed while the file is opened in flash), resolve that nativePath as the sourceFile, and use moveTo to rename the file on the hard drive.
Cheers for taking a look.
EDIT:
I've set up a test AIR app with only the following in it:
import flash.events.*;
import flash.filesystem.*;
var original = File.documentsDirectory;
original = original.resolvePath("D:\\Software\\test\\October.db");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("copy.db");
original.addEventListener(Event.COMPLETE, fileMoveCompleteHandler);
original.addEventListener(IOErrorEvent.IO_ERROR, fileMoveIOErrorEventHandler);
original.moveToAsync(destination);
function fileMoveCompleteHandler(event:Event):void {
trace(event.target); // [object File]
}
function fileMoveIOErrorEventHandler(event:IOErrorEvent):void {
trace("I/O Error.");
}
This fails, as does using D:\Software\test\October.db
I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?
I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?
You don't AFAIK. If your path is actually d:\software\test\october.db you can set a File ref like:
var original:File = new File();
original.nativePath = "d:\software\test\october.db";
I am new to log4php.
I would like to save the log files in the format /logs/UserId/Info_ddmmyyyy.php
where the UserId is dynamic data.
(I would basically like to save one log per user.)
Is there any way to change the log file path dynamically?
This behaviour is not supported by default. But you can extend LoggerAppenderFile (or RollingFile, DailyFile whatever your preference is) to support it.
Create your own class for that and make it load to your script.
Then extend from this class:
http://svn.apache.org/repos/asf/logging/log4php/trunk/src/main/php/appenders/LoggerAppenderFile.php
class MyAppender extends LoggerAppenderFile { ... }
You'll need to overwrite the setFile() method, similar to:
public function setFile($file) {
$path = getYourFullPath();
$this->file = $path.$file;
}
After all you need to use your new Appender in you config
log4php.appender.myAppender = MyAppender
log4php.appender.myAppender.layout = LoggerLayoutSimple
log4php.appender.myAppender.file = my.log
Please note, instead of giving your full path to the log file you now need to add a plain name. The full path (including username) must be calculated with your getYourFullPath() method.
Hope that helps!
Christian