Android Studio: Load a File into an Array [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have made a class that can save an array to file, yet, I need it to load the file back into an array inside of an Activity named SampleGridViewAdapter.
Text file format named gallerydump_img.txt:
https://mywebsite.com/path/samplefile.rtf
https://anotherwebsite.com/
https://thirdwebsite.com/example/
I have tried strings = LIST[i], with strings being the output from the file, i being the loop, and LIST being the array to output the file data to, line by line. More code below:
#Override
protected void onPostExecute(String[] strings) {
for(int i = 0; i < strings.length; i++) {
Log.e("GalleryFileDump", strings[i]);
ArrayToFile.writeArrayToFile(strings, Environment.getExternalStorageDirectory() + "/gallerydump_img.txt", "Eww, errors. Want a cookie? :: Unable to write to file gallerydump.bin. Check the report below for more information. :)");
strings = LIST[i]
}
}
Any help appreciated. Thanks!

This is what you'd want to read
public static List<String> readLines() {
File f = new File("gallerydump_img.txt");
BufferedReader r;
List<String> lines = new ArrayList<String>();
try {
r = new BufferedReader(new FileReader(f));
String line;
while (true) {
if ((line = r.readLine()) == null)
break;
lines.add(line);
}
} catch (Exception e) {
e.printStackTrace(); // file not found
}
return lines;
}
And this is what you'd want to write
public static void writeLines(List<String> lines) {
File f = new File("gallerydump_img.txt");
try {
PrintWriter pw = new PrintWriter(f);
for (String line : lines)
pw.println(line);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // file not found
}
}

I'm guessing what you have above doesn't compile? That's fine if it doesn't. I just want to be sure I understand the question.
Anyways, one way to serialize and deserialize strings to a file are as follows:
String[] readFile(String filename)
{
String[] strings;
BufferedReader reader = null;
try
{
reader = new BufferedReader( new InputStreamReader( new FileInputStream(filename)));
String str = reader.readLine();
while( null != str )
{
strings.add(str);
str = reader.readLine();
}
}
catch( IOException e )
{
e.printStackTrace();
}
if( null != reader )
{
reader.close();
}
return strings.toArray(new String[strings.size()]);
}
void writeFile(String filename, String[] strings )
{
PrintWriter writer = null;
try
{
writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename)));
for( int idx = 0; idx < strings.length; idx++ )
{
writer.println(strings[idx]);
}
}
catch( IOException e )
{
e.printStackTrace();
}
if( null != writer )
{
writer.close();
}
}

Related

Problems with reading in a text file, annoying error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to parse this text file, but I keep getting an error
"error reading file exception"
from my code. I am looking over and over at the code and I can't see what is wrong. Any ideas as to what can be the error? I know it's not the path to were the text file is, because I made a quick easy I/O program to test it, and it worked.
public static List<String> parseCode() {
List<String> inputList = new ArrayList<String>();
String File = "Sample1.txt";
String line = null;
try
{
FileReader fr = new FileReader(File);
BufferedReader br = new BufferedReader(fr);
String add = "";
boolean comment = false;
while((line = br.readLine()) != null)
{
String [] s = line.split(" ");
for(int i = 0; i < s.length; i++)
{
if(s[i].contains("/*"))
{
comment = true;
}
if(!comment)
{
add += s[i];
if(i < s.length-1 && add.length() > 0)
{
add += " ";
}
}
if(s[i].contains("*/"))
{
comment = false;
}
}
if(add.length() > 0)
{
inputList.add(add);
}
br.close();
}
}
catch(FileNotFoundException E)
{
System.out.println("File Not Found");
}
catch(IOException E)
{
System.out.println("Error Reading File Sample1.txt");
}
return inputList;
}
Your br.close(); is in the while-loop but should be after the loop.
This way you close the file after reading the first line.
So the fixed code (not tested) should look like this:
public static List<String> parseCode() {
List<String> inputList = new ArrayList<String>();
String File = "Sample1.txt";
String line = null;
try
{
FileReader fr = new FileReader(File);
BufferedReader br = new BufferedReader(fr);
String add = "";
boolean comment = false;
while((line = br.readLine()) != null)
{
String [] s = line.split(" ");
for(int i = 0; i < s.length; i++)
{
if(s[i].contains("/*"))
{
comment = true;
}
if(!comment)
{
add += s[i];
if(i < s.length-1 && add.length() > 0)
{
add += " ";
}
}
if(s[i].contains("*/"))
{
comment = false;
}
}
if(add.length() > 0)
{
inputList.add(add);
}
}
br.close();
}
catch(FileNotFoundException E)
{
System.out.println("File Not Found");
}
catch(IOException E)
{
System.out.println("Error Reading File Sample1.txt");
}
return inputList;
}

Cannot get String Value from Array list: Getting only [Ljava.lang.string # [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm parsing Outlook SCV file to ArrayList.
Then i want to get String values of the Array list i'm getting.
Here is the code:
if(arr != null){
try{
for (int i = 1; i < arr.size(); i++) {
oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
StringBuilder strBuild = new StringBuilder();
strBuild.append(String.valueOf(oneRow.get(j).toString()));
Here is the ArrayList:
No matter what i tried, i can't get the String Value.
What i get is : [Ljava.lang.string #....
Here is the Class that makes the ArrayList which getting the CSV file and building the ArrayList:
public class ReadingCSV {
InputStream inputStream;
public ReadingCSV(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
ArrayList resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
Note :- This Code is compiled and run using jdk V1.8
try this out this is a working code. you can Manipulate as per your need.
public List<String> read(){
ArrayList<String> resultList = new ArrayList(); //A Type-Safety (String) ArrayList
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(","); //row is String Array Object
for(String eachWord : row) //Iterate each String from the array
resultList.add(eachWord); // add String to the Type-Safe ArrayList.
}
}catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
update Your another code with this
if(arr != null){
for (int i = 1; i < arr.size(); i++) {
ArrayList<String> oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
strBuild.append(oneRow.get(j));
}
}
System.out.println(strBuild.toString());
}
This Code is perfectly Working. You may try it by your own. If any issue you may put a comment .
Why are you double convert to String this:
strBuild.append(String.valueOf(oneRow.get(j).toString()));
I think,this is helps you:
Help link

How do I remove all occurrences of "," and "[" from the output in java?

Here is my code. The input consists of names of anime(japanese cartoons) which i have stored it in testfile in anime.txt and I am arranging them in alphabetical order and writing it back into another file name animeout.txt.
The input file does not contain any comma or square bracket but the output file has it.
public class Main {
public static ArrayList<String> read(String filePath) throws IOException {
ArrayList<String> names = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
int numRead = 0;
String line;
while ((line = reader.readLine()) != null) {
names.add(line + "\n");
numRead++;
}
System.out.println("\n\n count " +numRead);
reader.close();
System.out.println(names);
return names;
}
public static void write(ArrayList<String> input) throws IOException
{
File file = new File("Animeout.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(input);
writer.flush();
writer.close();
}
public static void main(String args[]) throws IOException
{
ArrayList<String> names2 = new ArrayList<String>();
String path= "anime.txt";
String test;
names2 = read(path);
Collections.sort(names2, null);
// System.out.println(names2);
write(names2);
}
}
Input file has about 200 lines. Below is just a small example
One piece
Naruto/naruto shippuden
Bleach
Fullmetal alchemist brotherhood
Fate/stay night
Fairy tale
Blue exorcist
Soul eater
Death note
Output file contains , and [
count 105
[11 eyes
, A certain magical index
, A certain magical index II
, Aldnoah.Zero
, Angel beats!
, Another
, Asu no yoichi
, Bay blade
, Beelzebub
, Ben-To
String str = "[12,34,45]";
String out = str.replaceAll(",|\\[|\\]","");
output:
123445
Why are you using a ObjectOuputStream? That is intended for when you want to serialise Java objects and restore them later. I don't see why you need it here.
Just use a FileWriter, like so:
public static void write(ArrayList<String> input) throws IOException
{
try
{
File file = new File("Animeout.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < input.size(); i++) {
fw.append(input.get(i) + "\n");
}
}
finally
{
try {
if (fw != null)
fw.close();
}
catch (Exception e) {
// ignore
}
}
}
Your write method is unfortunate. Try something like this instead (and remove the + "\n" when reading the lines):
public static void write(ArrayList<String> lines) throws IOException
{
File file = new File("Animeout.txt");
PrintStream ps = null;
try {
ps = new PrintStream(file);
for (final String line : lines) {
ps.println(line);
}
} finally {
if (ps != null) { ps.close(); }
}
}
The ObjectOutputStream you are using is not appropriate for simply writing lines of text.
Finally, if all you want to do is sorting the lines of a text file, at least on a POSIX system, you can just do it with
$ sort anime.txt > Animeout.txt
from the command line.

More Effective way of picking a part a String from JTextPane?

It's not that my code doesn't work, but I am doubting whether it's very efficient or not. My theory is, that it isn't xD
I have a JTextPane where I have to take the text in it (Making a new line every time the JTextPane got a new line basically), and put it into a .txt file. As I said everything works but I am doubting the implementation of it.
This is the part I am doubting:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
This is the entire thing just for reference:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
File f = new File("JServer_Log.txt");
BufferedWriter bw = null;
FileWriter fr = null;
try {
if(f.exists()) {
fr = new FileWriter(f,true);
} else {
fr = new FileWriter(f);
}
} catch (IOException e) {
// Nothing to do really.
}
try {
bw = new BufferedWriter(fr);
Iterator<String> itr = log.iterator();
bw.newLine();
while(itr.hasNext()) {
bw.write(itr.next());
bw.newLine();
}
} catch (IOException e) {
// Nothing to do really. We lost the log?
} finally {
try {
bw.close();
} catch(IOException ioe) {
// The program is closing any way.
}
}
}
It seems that you just need to make sure you use the platform's appropriate newline sequence. You can just say s = s.replace("\n", System.getProperty("line.separator")) and then write that whole string directly to file. In fact, the way I see it, this is all the code you need (except maybe for exception handling, up to you):
public void printLog() throws IOException {
final FileWriter w = new FileWriter("JServer_Log.txt", true);
try {
w.write(logTextArea.getText().replace("\n",
System.getProperty("line.separator")));
} finally { w.close(); }
}
For information, the first code can be replaced by:
List<String> log = Arrays.asList(logTextArea.getText().split("\n"));
but other answers give you a way to replace the whole method.
Why bothering, to use JTextComponents.write(Writer out) throws IOExceptionwrite() this is pretty accepting newline, tabs, e.i. that came from Native OS
use split:
String[] log = s.split("\n");

Best way to read data from a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to read a text file
In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.
I want to read the words into a string array. But how do I read the data first?
You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
lines.add(reader.readLine());
}
Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();
for(int i = 1; i <= lines; i++) {
words.add(sc.nextLine());
}
String[] w = words.toArray(new String[]{});
Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.FileReader("filename.txt"));
String str;
while((str = in.readLine()) != null)
{
...
}
}
catch(java.io.IOException ex)
{
}
You could use reflection and do this dynamically:
public static void read() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
String line = reader.readLine();
while (line != null) {
if (Integer.class.isAssignableFrom(line.getClass())) {
int number = Integer.parseInt(line);
System.out.println(number);
} else {
String word = line;
System.out.println(word);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources