I have tried code from MallikarjunM, but it does not work for me :-(. I have it little rewrite it to my basic Android Studio project with empty activity with one textViev "pokusnejText".
here is my code MainActivity.kt:
package com.example.zapisdosouboru
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.TextView
import java.io.File
import java.io.PrintWriter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val pokusnejText = findViewById<TextView>(R.id.pokusnejText)
var answer : String = ""
val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/smazat" )
var success = true
if (!sd_main.exists()) {
success = sd_main.mkdir()
if (success) {
answer = "folder created"
} else {
answer = "folder can not be created"
}
}
if (success) {
val sd = File("testingFile.txt")
if (!sd.exists()) {
success = sd.mkdir()
}
if (success) {
// directory exists or already created
val dest = File(sd, "testingFile.txt")
try {
// response is the data written to file
PrintWriter(dest).use { out -> out.println(answer) }
answer = "writed to" + sd.toString()
} catch (e: Exception) {
answer = "can not be written"
}
} else {
answer = "folder or file does not exists"
}
}
pokusnejText.text = answer
}
}
and here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zapisdosouboru">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
first what I have rewrite was
val sd_main = File(Environment.getExternalStorageDirectory()+"/yourlocation")
to
val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/yourlocation" )
because without toString() was plus marked red ... but it still does not work and answers that it can not create the folder... I have tried it in Android Studio emulator with android 6.0
Some additional questions: I am very confused with function File() used in code one time with one parameter and second times with two. Does exists for Kotlin some web page similar http://www.cplusplus.com/ - I can not find any so helpful as for c++.
Thanks for help fik236