Reading a textfile in android studio - java

Hi I'm currently having issues with reading in a file in android studio. The file I want to read in is just a simple text file called test. This is the path of the file C:\Users\John\Documents\MadLibs\app\src\main\res\raw\test.txt. Here's what I'm trying:
BufferedReader br = new BufferedReader(new FileReader(getResources().openRawResourceFd(R.raw.test)));
I'm relitively new to android studio and really don't understand how to read in files. I assumed its just like java however everything I've tried fails. Anyone have any ideas?

Reading a textfile in android studio
FileInputStream fileInputStream=openFileInput("file.txt");
InputStreamReader InputRead= new InputStreamReader(fileInputStream);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String rs=String.copyValueOf(inputBuffer,0,charRead);
s +=rs;
}
InputRead.close();
Log.d(TAG,s);

To read a text file as a string, you can use the following method:
// #RawRes will gives you warning if rawId is not from correct id for raw file.
private String readRawFile(#RawRes int rawId) {
String line;
try {
InputStream is = getResources().openRawResource(rawId);
// read the file as UTF-8 text.
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// Or using the following if API >= 19
//BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
inputStream.close();
line = result.toString();
} catch (IOException e) {
line = null;
}
return line;
}

Related

How to transform a ByteArrayOutputStream in order to loop using readline

I want to download a file using FTP, and then keep the file in memory and simply loop over the lines.
I am downloading the file like this so far:
ByteArrayOutputStream bos = new ByteArrayOutputStream()
ftp.retrieveFile("inventory.csv", bos)
I'm not sure how to go from a ByteArrayOutputStream to be able to loop each line.
https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#retrieveFile(java.lang.String,%20java.io.OutputStream)
This is the idea I had in mind, save minor overlooks, it should help you:
ByteArrayOutputStream bos;
BufferedReader bufferedReader;
FTPClient ftp;
String line;
ArrayList<String[]> values;
try{
bos = new ByteArrayOutputStream();
ftp = new FTPClient();
if (ftp.retrieveFile("inventory.csv", bos)){
values = new ArrayList<>();
bufferedReader = new BufferedReader(new StringReader(new String(bos.toByteArray())));
while ((line = bufferedReader.readLine()) != null){
values.add(line.split(","));
}
// Then you could switch ArrayList<String[]> for just String[]
}
}
catch(Exception x){
}
finally{
if (bufferedReader != null)
bufferedReader.close();
if (bos != null)
bos.close();
}
You could use retrieveFileStream() instead and then read line by line in a try-with-resources block using a BufferedReader.
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(ftp.retrieveFileStream("inventory.csv"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
// do something with line
}
} catch (IOException e) {
// handle error
}
The code assumes that the file is encoded in UTF-8. If a different encoding is used make sure to replace StandardCharsets.UTF_8 accordingly.
The advantage over an intermediate ByteArrayOutputStream is that at no point your program needs to have a copy of the whole file content in memory.

Is this a good way of reading from a text file?

I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this:
private static String load(final String path)
{
String text = null;
try
{
final FileReader fileReader = new FileReader(path);
fileReader.read(CharBuffer.wrap(text));
// ...
}
catch(IOException e)
{
e.printStackTrace();
}
return text;
}
In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?
If you want to read the file line by line:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you want to read the complete file in one go:
String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)
I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
fr.close();
return sb.toString();

Unable to a read a large file using BufferedReader in Java

I am trying to read a file using BufferedReader, but when I tried to print, It is returning some weird characters.
Code of reading file is:
private static String readJsonFile(String fileName) throws IOException{
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null ){
sb.append(line);
System.out.println(line);
line=br.readLine();
}
return sb.toString();
} finally{
br.close();
}
}
This function is being called as :
String jsonString = null;
try {
jsonString = readJsonFile(fileName);
} catch (IOException e) {
e.printStackTrace();
}
But when I tried to print this in console using System.out.println(jsonString);, It is returning some fancy pictures.
Note: It is Working file when file size is small.
Is there any limit on size of file it can read ?
You're using the platform default encoding to read the file, which is probably encoded in UTF8. Check the actual encoding of the file, and specify the encoding:
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("...", StandardCharsets.UTF_8));
Note that since you simply want to read everything from the file, you could simply use
String json = new String(Files.readAllBytes(...), StandardCharsets.UTF_8);

How can I read a text file in android with Turkish characters?

I want to read a text file and I can read with below written code. But my text file include Turkish characters like "ü", "ç", "ğ", "ö"... When I read that text file, I can see these characters. For example, my word which written in text file is "okçu" but I see on my phone like "ok?u". How can fix it?
public static String readTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputreader);
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
while ((line = bufferedreader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
} catch (IOException e) {
return null;
}
return stringBuilder.toString();
}
I faced this problem when I received the response from my HttpClient for the first time. I managed to solve it by specifying the encoding within the InputStreamReader object's instantiation. I hope it might help you as well.
InputStream inputStream = ctx.getResources().openRawResource(resId);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF8"),8);

Java read in single file and write out multiple files

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}

Categories