Showing posts with label Write file. Show all posts
Showing posts with label Write file. Show all posts

Thursday, February 21, 2019

Swift write file

We want to save a text string in to user phone. Copy in to viewDidLoad.
let file = "write.txt"
let text = "This is example text"
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
                    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)       
                    do {
                        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
                    }
                    catch {/* error handling here */}
                }
To check if data write or not, we read file and set to a textview.
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
        let path = documentsPath.stringByAppendingPathComponent("write.txt")
        var read : String = ""
     do {
            try read = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
            gi.text = read
            gi.font = UIFont.italicSystemFontOfSize(17)
            gi.textColor = UIColor.blueColor()
            gi.textAlignment = NSTextAlignment.Center
             }
        catch let error as NSError {
            // print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
        }
Run to see result.

When practical, we use to write to lines, new line will below old line, that easy to read for use.
This function below write data in to new line.
func write(content: String, _ fileName: String) {
     let contentToAppend = content+"\n"
     let filePath = NSHomeDirectory() + "/Documents/" + fileName
   if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
 fileHandle.seekToEndOfFile()
fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
   }
        else {    
            do {
                try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            } catch {
                print("Error creating \(filePath)")
            }
        }

    }

Wednesday, February 20, 2019

Java write data

In any class, choose a textView to set text.
Copy the code lines to below findViewByid.
String write="This is example text";
try {
FileOutputStream fos = openFileOutput("text.txt", Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
     osw.append(write);
     osw.flush();
     osw.close();
      } catch (FileNotFoundException e) {            
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }  
Here we write a String to file name text.txt, to make sure the data has write, we read that file and set text to textView.
String read="";
try {
          String FILE_NAME = "text.txt";          
          FileInputStream fIS = openFileInput(FILE_NAME);              
          byte[] arrayData = new byte[fIS.available()];
          if((fIS.read(arrayData))!= -1){
          String fileContent = new String(arrayData);
          read=fileContent;
          tv.setText(read);
          }   
          fIS.close();             
          } catch (Exception e) {
              
               //Log.e("Error", e.toString());
          }
Run to see text has read success.
If you quit and reopen class many times, you will see many string add to textView, because file text.txt always there and programme continue to write many times.