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;
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
public static void main(String[] args) {
BufferedReader bf = null;
BufferedWriter bw = null;
try {
FileReader fr = new FileReader("File.txt");
FileWriter fw = new FileWriter("Output.txt");
bf = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//Skip the first line
bf.readLine();
String line;
List<String> finalCheck = new ArrayList<String>();
//Read the file line by line and add the first number of each line (as a String) to the finalCheck List
while((line = bf.readLine()) != null){
String [] idArray = line.split(",");
String idCheck = idArray[0];
finalCheck.add(idCheck);
}
//Checking for any duplicates within the ID's and displaying them on
int i = 0;
int j = 0;
for (i = 0; i <= finalCheck.size(); i++) {
for (j = i + 1; j <= finalCheck.size(); j++) {
String [] array = new String[finalCheck.size()];
finalCheck.toArray(array);
if(array[i].equals(array[j])) { //This is Line 43
fw.write("Duplicate at line: " + array[i]);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Cannot read the file");
} finally {
try {
bf.close();
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I keep getting the error message shown in the title, and I am not sure how to fix it. Any idea's on what is going wrong to cause the issue? I added a note in the code to show exactly where Line 43 is, but if any additional information is needed please let me know and I will be more than happy to add it.
j <= finalCheck.size() should be j < finalCheck.size().
For an array of size x, In Java, the last index is x - 1 because arrays in Java start at index 0.
When I delete a record first before inserting a new record, I can do it, and after deleting I can add new record. But if I insert a new record first then my delete function is not working. Based on my research, it's mainly because the input/output is not closed properly but I have already done that, please take a look at my source code thank you.
Insert record
public void RegCustomer()
{
try
{
File F = new File("Customer.txt");
FileWriter fw = new FileWriter(F, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(F, true)));
pw.println(this.Name+","+this.CheckInDate+","+this.CheckOutDate+","+this.Floor+","+this.RoomID+","+this.ICNumber+","+this.Contact+","+this.Email);
pw.flush();
pw.close();
fw.close();
bw.close();
}
catch(Exception e)
{
}
}
Delete Record
public boolean delcus(String Target)
{
boolean success = false;
File F = new File("Customer.txt");
File Ftc = new File("Temp.txt");
try
{
FileReader fr = new FileReader(F);
BufferedReader br = new BufferedReader(fr);
PrintWriter pr = new PrintWriter(Ftc);
String line = br.readLine();
while (line!=null)
{
String[] wordsinLine = line.split(",");
if (wordsinLine[0].equals(Target))
{
}
else
{
pr.println(line);
success = true;
}
line = br.readLine();
}
if (success)
{
pr.flush();
pr.close();
br.close();
fr.close();
}
}
catch (Exception e)
{
}
F.delete();
File dump = new File("Customer.txt");
Ftc.renameTo(dump);
return success;
}
I have another method that checks for several conditions before triggering the insert method.
public int checkroom()
{
int check = 0;
int ciDay = this.CheckInDate/10000;
int ciMonth = (this.CheckInDate/100)%100;
int coDay = this.CheckOutDate/10000;
int days = coDay - ciDay;
String name;
int Dbcid;
int Dbcod;
int DbFloor;
int DbRoomID;
try
{
File F = new File("Customer.txt");
FileReader Fr = new FileReader(F);
BufferedReader Reader = new BufferedReader(Fr);
Scanner Sc = new Scanner(Reader);
Sc.useDelimiter("[,\n]");
while(Sc.hasNext())
{
name = Sc.next();
Dbcid = Sc.nextInt();
Dbcod = Sc.nextInt();
DbFloor = Sc.nextInt();
DbRoomID = Sc.nextInt();
if (days <= 7)
{
if (DbFloor == this.Floor && DbRoomID == this.RoomID)
{
int DbcidDay = Dbcid/10000;
int DbcidMonth = (Dbcid/100)%100;
int DbcodDay = Dbcod/10000;
if(ciMonth == DbcidMonth)
{
if (ciDay >= DbcidDay && ciDay < DbcodDay)
{
check = 2;
}
else if (coDay >= DbcidDay && coDay < DbcodDay)
{
check = 3;
}
else if (ciDay <= DbcidDay && coDay >= DbcodDay)
{
check = 4;
}
else
{
check = 1;
}
}
else
{
check = 1;
}
}
else
{
check =1;
}
}
else
{
check =5;
}
}
if(check > 0)
{
Sc.close();
Reader.close();
Fr.close();
}
}
catch (Exception e)
{
}
return check;
}
There are a few issues I can see:
You need to close your streams in a finally clause (or, better still, use a try-with-resource). Otherwise, if an exception is thrown that interrupts the normal program flow, your stream will not be closed immediately.
You should only close the outermost stream object (so e.g. your BufferedReader, but not the FileReader)
You are swallowing exceptions. At least do a printStackTrace() on the exceptions you catch so you can see if any are actually thrown.
Avoid methods like File.delete() that don't throw exceptions in the case of an error. Instead, use the equivalent methods on the Files.class, which throw exceptions in the event of an error.
Incidentally, although it's not an issue as such, you don't need to call flush() just before close()-- the latter automatically flushes before closing.
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
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();
}
}
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");