I am trying to send html file content to request parameter.
The problem area is on the server side, getting some extra characters.
<!Document....> the other side ?<!Document...>
Why this "?" mark comes.
Can any one help me to figure out.
Thanks in advance.
Finally I got solution of my problem
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}
You will find more detail in this link..
http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
Related
I can't read with Acrobat Reader a created file.pdf on my Android Studio (pdf is an exemple, I also need .jpg or .txt) because there is an error.
private void uriGetDocumentGedFindById(Integer id, String extension) throws Throwable {
String url = PreferencesFragment.DEFAULT_SERVER_URL_DOCUMENTGEDFINDBYID + id;
MyHttpClient client = new MyHttpClient(url);
URL url2 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
responsUriGetDocumentGedFindById = client.getResponseHttpURLConnection(urlConnection);
String name = id.toString() + "." + extension;
saveFile(responsUriGetDocumentGedFindById, name, PreferencesFragment.DOCUMENTS_FOLDER);
}
public void saveFile(String json, String name, String path) throws IOException {
try {
FileWriter writer = new FileWriter(
new File(mContext.getFilesDir().toString() + path, name));
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseHttpURLConnection(HttpURLConnection urlConnection) {
StringBuffer response = null;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
I receive this from my back : via Postman on the left (this is functional, I can read the pdf), in my file.pdf (on Android Studio) on the right (there is an error with Acrobat Reader)
So first I can't read my file.pdf and second the file.pdf is bigger than the original whitout any additional information (original 200Ko and my file.pdf 400Ko) this is perhaps a clue...
My back :
#Override
public ResponseEntity<Resource> findByIdDocumentGed(Integer id) throws FileNotFoundException {
DocumentGed documentGed = documentGedService.findByIdDocumentGed(id);
InputStreamResource resource = null;
try {
Integer idFile = documentGed.getFichierCourant().getId();
String extensionFile = documentGed.getFichierCourant().getTypeFichier().getExtension();
File file = new File(nasIris + "/ged/import/" + idFile + "." + extensionFile);
resource = new InputStreamResource(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (resource == null) {
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.OK);
}
Have you tried to use FileOutputStream instead FileWriter ?
I am developing an Android application in which I need to show the saved WiFi passwords in the mobile or tablet. Like for example, if my mobile is connected to any network that n/w password is saved in my mobile. I want to get it.
Unless you are rooted, I don't know of any way to do it. If you are rooted, or are willing to root your Galaxy for those nice guy points, you should be able to use a file manager (ASTRO, Root Browser, etc.) to find it.
Use the file manager to locate your data/misc/file folder, then look for wpa_supplicant.conf, or I assume it could be wep_supplicant.conf if his/her network is using WEP instead of WPA. Open the .conf file using a text editor (which is probably built into your file manager application, if not, add that to your shopping list). You should be able to read the password in plain text at that point.
Your Comments helped me to some extent to find out the solution to my question. Especially #Namik Kalavadia I am talking about you Thanks for that.
Finally here is the solution.
public class MainActivity extends Activity {
File file;
public StringBuffer ab;
public File savefile;
public InputStream in = null;
public String filename = "wpa_supplicant.conf";
public File ot_path;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
ot_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d("aaa", ""+ot_path.toString());
}
public void path(View v){
getPath();
}
private void getPath(){
file = Environment.getRootDirectory();
String ext = ".conf";
File list[] = file.listFiles();
ab = new StringBuffer();
if(list!=null){
fileNameSearch(list);
}
}
public void fileNameSearch(File list[]){
if(list!=null){
for(int f = 0;f<list.length;f++){
ab.append(list[f].getName()+"\n");
File fi = list[f];
String path = fi.getPath();
if(fi.isDirectory()){
fileNameSearch(fi.listFiles());
}
else if(path.endsWith(".conf")){
if(path.contains(filename)){
try{
File fileForParse = copyFile(path,ot_path);
in = new FileInputStream(fileForParse);
getStringFromInputStream(in);
Log.d("aaa", "conf I got it"+path);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
else{
Log.d("aaa", "List is null in method");
}
}
private File copyFile(String inputPath, File outputPath) {
InputStream input = null;
OutputStream out = null;
try {
if (!outputPath.exists())
{
outputPath.mkdirs();
}
savefile = new File(outputPath,filename);
if (!savefile.exists()) {
savefile.createNewFile();
File f = new File(inputPath);
Log.d("aaa",""+f.length());
input = new FileInputStream(inputPath);
out = new FileOutputStream(savefile);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
Log.d("aaa",""+savefile.length());
input.close();
input = null;
out.flush();
out.close();
out = null;
}
} catch (FileNotFoundException fnfe1) {
Log.e("aaa", fnfe1.getMessage());
return null;
}
catch (Exception e) {
Log.e("aaa", e.getMessage());
return null;
}
return savefile;
}
#SuppressWarnings("deprecation")
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
if(line.contains("ssid")||line.contains("psk")){
sb.append(line+"\n");
}
if(line.contains("}")){
sb.append("-----------------\n");
}
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.setTitle("Lis of WiFi Passwords Saved in your Mobile");
ad.setMessage(sb);
ad.setButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
ad.show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
It is not possible as far as I know . It will be a security problem if sdk tools allows to do so .
Retrieving saved Wifi password programatically is not possible due to security issue.If you root your phone you may able to get it,but that too in an encrypted form.
I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format
I am trying to get last 10 rows from file but not able to fetch.
i have two activities:
in the first, i want to write text from an EditText to a file.
in the second activity i try to read the stored data and write it to a textView
public class Date_Location extends Activity {
ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;
private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.date_location);
editTextDate = (EditText) findViewById(R.id.editText1);
editTextLocation = (EditText) findViewById(R.id.editText2);
editTextEdit = (EditText) findViewById(R.id.editText3);
imageView = (ImageView) findViewById(R.id.next);
}
public void goNext(View view) {
String Date = editTextDate.getText().toString();
String Location = editTextLocation.getText().toString();
String Comment = editTextEdit.getText().toString();
writeToFile(Date);
writeToFile(Location);
writeToFile(Comment);
Intent intent = new Intent(this, Detail_Data.class);
startActivity(intent);
Date_Location.this.finish();
}
private void writeToFile(String data) {
String newline = "\r\n";
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
FILENAME, Context.MODE_APPEND));
oswName.write(newline);
oswName.write(data);
oswName.close();
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
And my second Activity is below
public class Detail_Data extends Activity {
TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_data);
textView1 = (TextView) findViewById(R.id.textView1);
imageView = (ImageView) findViewById(R.id.imageView2);
String date = readFromFile();
textView1.setText(date);
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
public void goNext(View view) {
imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);
Intent intent = new Intent(this, Agreement.class);
startActivity(intent);
Detail_Data.this.finish();
}
}
please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.
Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Secondly, don't forget flush()
oswName.write(data);
oswName.flush();
oswName.close();
Then, there is something wrong with your readFromFile() method,
remove this line from while loop
stringBuilder.append(receiveString+'\n');
and add this right after the while loop
for(String str : bandWidth)
stringBuilder.append(str + "\n");
readFromFile() should be like following
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
for(String str : bandWidth)
stringBuilder.append(str + "\n");
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
After opening the input/output stream, use that methods:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Files {
public static String readStringFile(FileInputStream fis) throws java.io.IOException {
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
return fileContent.toString();
}
public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
fos.write(text.getBytes());
}
}
First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.
You store each line to list and remove 0 position only if list size = 10
So as 1st step store all file in list:
Instead
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
Write
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
After copy last 10 lines to new list.
For example if you have :
List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));
Than with subList:
List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
It will copy last 10 list items to new list.
Totally it should be something like:
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
I have a text file added as a raw resource. The text file contains text like:
b) IF APPLICABLE LAW REQUIRES ANY WARRANTIES WITH RESPECT TO THE
SOFTWARE, ALL SUCH WARRANTIES ARE
LIMITED IN DURATION TO NINETY (90)
DAYS FROM THE DATE OF DELIVERY.
(c) NO ORAL OR WRITTEN INFORMATION OR
ADVICE GIVEN BY VIRTUAL ORIENTEERING,
ITS DEALERS, DISTRIBUTORS, AGENTS OR
EMPLOYEES SHALL CREATE A WARRANTY OR
IN ANY WAY INCREASE THE SCOPE OF ANY
WARRANTY PROVIDED HEREIN.
(d) (USA only) SOME STATES DO NOT
ALLOW THE EXCLUSION OF IMPLIED
WARRANTIES, SO THE ABOVE EXCLUSION MAY
NOT APPLY TO YOU. THIS WARRANTY GIVES
YOU SPECIFIC LEGAL RIGHTS AND YOU MAY
ALSO HAVE OTHER LEGAL RIGHTS THAT
VARY FROM STATE TO STATE.
On my screen I have a layout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1.0"
android:layout_below="#+id/logoLayout"
android:background="#drawable/list_background">
<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/txtRawResource"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dip"/>
</ScrollView>
</LinearLayout>
The code to read the raw resource is:
TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource);
txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample);
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
return null;
}
return byteArrayOutputStream.toString();
}
The text is shown but after each line I get the strange characters []. How can I remove the characters? I think it's a newline.
You can use this:
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.help);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("Error: can't show help.");
}
What if you use a character-based BufferedReader instead of byte-based InputStream?
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
...
line = reader.readLine();
}
Don't forget that readLine() skips the new-lines!
Well with Kotlin u can do it just in one line of code:
resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }
Or even declare extension function:
fun Resources.getRawTextFile(#RawRes id: Int) =
openRawResource(id).bufferedReader().use { it.readText() }
And then just use it straightaway:
val txtFile = resources.getRawTextFile(R.raw.rawtextsample)
If you use IOUtils from apache "commons-io" it's even easier:
InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams
Dependencies: http://mvnrepository.com/artifact/commons-io/commons-io
Maven:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Gradle:
'commons-io:commons-io:2.4'
Rather do it this way:
// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(id);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] readBuffer = new byte[4 * 1024];
try {
int read;
do {
read = is.read(readBuffer, 0, readBuffer.length);
if(read == -1) {
break;
}
bout.write(readBuffer, 0, read);
} while(true);
return bout.toByteArray();
} finally {
is.close();
}
}
// reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
return new String(getResource(id, getContext()), encoding);
}
// reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}
From an Activity, add
public byte[] getResource(int id) throws IOException {
return getResource(id, this);
}
or from a test case, add
public byte[] getResource(int id) throws IOException {
return getResource(id, getContext());
}
And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.
#borislemke you can do this by similar way like
TextView tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
This is another method which will definitely work, but I cant get it to read multiple text files to view in multiple textviews in a single activity, anyone can help?
TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Here goes mix of weekens's and Vovodroid's solutions.
It is more correct than Vovodroid's solution and more complete than weekens's solution.
try {
InputStream inputStream = res.openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
reader.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// process exception
}
Here is an implementation in Kotlin
try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
Here is a simple method to read the text file from the raw folder:
public static String readTextFile(Context context,#RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, size);
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
1.First create a Directory folder and name it raw inside the res folder
2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt....
3.copy and paste the text you want inside the .txt file you created"articles.txt"
4.dont forget to include a textview in your main.xml
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gettingtoknowthe_os);
TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
helloTxt.setText(readTxt());
ActionBar actionBar = getSupportActionBar();
actionBar.hide();//to exclude the ActionBar
}
private String readTxt() {
//getting the .txt file
InputStream inputStream = getResources().openRawResource(R.raw.articles);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
int i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Hope it worked!
InputStream is=getResources().openRawResource(R.raw.name);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();
while(line!=null)
{
data.append(line+"\n");
}
tvDetails.seTtext(data.toString());
Here's a one liner for you:
String text = new BufferedReader(
new InputStreamReader(getResources().openRawResource(R.raw.my_file)))
.lines().reduce("\n", (a,b) -> a+b);
val inputStream: InputStream = resources.openRawResource(R.raw.product_json)
val reader: Reader = BufferedReader(InputStreamReader(inputStream, "utf-8"))
val writer: Writer = StringWriter()
val buffer = CharArray(1024)
reader.use { it ->
var n: Int
while (it.read(buffer).also { n = it } != -1) {
writer.write(buffer, 0, n)
}
}
val stringVal = writer.toString()