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

Thursday, February 21, 2019

Swift read txt file

Drag a txt file in to project.

Declare a textView name gi. Copy in to viewDidLoad.
let path = NSBundle.mainBundle().pathForResource("t1", ofType: "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)")
        }
If you put txt inside a folder, for example, raw folder, let change "t1" near pathForResource to "raw/t1"
If want to read file to lines and add to an array, use this code.
do {
            try read = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
            var ar = read.componentsSeparatedByString("\n")
            let t=ar[2]
          
            gi.text = t
            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)")
        }


We read to an array and set row 3 to textView.

Wednesday, February 20, 2019

Java read file txt

We want to read a txt file, first, use notepad to create a txt file, save it with UTF-8 Encoding.

Create a folder name raw, copy file txt in to it.

In class, we need a textView to show, name it tv.
Copy this lines below findViewById.
InputStream in = this.getResources().openRawResource(R.raw.tho);
     try
      {
     byte[] buffer = new byte[in.available()];
     while (in.read(buffer) != -1);
     String jsontext = new String(buffer);

       tv.setText(jsontext);         
          
     }
   catch (IOException e)
     {
             //return null;
}
Press Ctrl+Shift+O to import libraries.

Run to see the result.

Now we want to read file to lines, add them in to an array.
Declare an arraylist.
ArrayList<String> ar = new ArrayList<String>();
Replace the codes above by this lines.
String line = "";
     try {
InputStream  In = this.getResources().openRawResource(R.raw.tho);
               InputStreamReader inputReader = new InputStreamReader(In);
               BufferedReader BR = new BufferedReader(inputReader);
     while ((line = BR.readLine()) != null) {
          ar.add(line);
     }
BR.close();

} catch (IOException e) {
e.printStackTrace();
}
tv.setText(ar.get(2));
Here we read file to an array and set the third line to textView.