Java Program keeps inserting the same line into my file - java

so I am trying to read a file and add two lines of code to it at the top. So far that hadn't been working so I tried just reading the lines and writing them back. This was a major failure. It only writes to one of the files in the directory and just keeps filling it with the xmlopentag even though its been commented out, over and over. If anyone has any ideas it would be appreciated.
ArrayList<String> lines = new ArrayList();
BufferedReader reader = null;
String xmlstylesheet = "<?xml-stylesheet type=\"text/xsl\" href=\""+stylefilename+"\"?>";
String xmlopentag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
for(int i=0;i<files.length;i++) {
lines.clear();
try {
reader = new BufferedReader(new FileReader(files[i]));
String text = null;
while ((text = reader.readLine()) != null) {
lines.add(text);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
//lines.add(1, xmlstylesheet);
//lines.add(0, xmlopentag);
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(files[i])));
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}

writer.write(lines.get(i));
should probably be
writer.write(lines.get(j));

for loop for PrintWriter operation is having an index j for iteration but using i to get the list value
please check it properly and change below code
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
to
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(j));
}

Related

Java too many open files exception

I have a problem on my code; basically I have an array containing some key:
String[] ComputerScience = { "A", "B", "C", "D" };
And so on, containing 40 entries.
My code reads 900 pdf from 40 folder corresponding to each element of ComputerScience, manipulates the extracted text and stores the output in a file named A.txt , B.txt, ecc ...
Each folder "A", "B", ecc contains 900 pdf.
After a lot of documents, an exception "Too many open files" is thrown.
I'm supposing that I am correctly closing files handler.
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader = new FileReader(dizionario);
} catch (FileNotFoundException e) { }
try {
BufferedReader bufferedReader = new BufferedReader(fileReader);
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (! line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else { System.err.println("Dictionary file not found."); }
bufferedReader.close();
fileReader.close();
fileWriter.close();
} catch (IOException e) { return false;}
catch (NullPointerException ex ) { return false;}
finally {
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
But the error still comes. ( it is thrown at:)
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
Thank you.
EDIT: SOLVED
I found the solution, there was, in the main function in which writeOccurencesFile is called, another function that create a RandomAccessFile and doesn't close it.
The debugger sais that Exception has thrown in writeOccurencesFile but using Java Leak Detector i found out that the pdf were already opened and not close after parsing to pure text.
Thank you!
Try using this utility specifically designed for the purpose.
This Java agent is a utility that keeps track of where/when/who opened files in your JVM. You can have the agent trace these operations to find out about the access pattern or handle leaks, and dump the list of currently open files and where/when/who opened them.
When the exception occurs, this agent will dump the list, allowing you to find out where a large number of file descriptors are in use.
i have tried using try-with resources; but the problem remains.
Also running in system macos built-in console print out a FileNotFound exception at the line of FileWriter fileWriter = ...
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
try (FileWriter fileWriter = new FileWriter( "files/" + categoria + ".txt" , true)) {
try (FileReader fileReader = new FileReader(dizionario)) {
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (!line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else {
System.err.println("Dictionary file not found.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
This is the code that i am using now, although the bad managing of Exception, why the files seem to be not closed?
Now i am making a test with File Leak Detector
Maybe your code raises another exception that you are not handling. Try add catch (Exception e) before finally block
You also can move BufferedReader declaration out the try and close it in finally

Setting value of an attribute when uploading file to database

I have a .csv file "Salesman" that will be uploaded to the sqlite database. This file contains details about a Salesman.
A sample row for Salesman:
-----------
|code|name|
-----------
|0001|Jon|
-----------
|0002|Stu|
DDL for Salesman:
CREATE TABLE salesman (
code INTEGER NOT NULL,
name TEXT NOT NULL,
isSelected INTEGER NOT NULL,
PRIMARY KEY (
code
)
);
The attribute isSelected acts as a tag stating that the Salesman has been selected, thus cannot be chosen again.
This is my code for getting Salesman details from .CSV file:
public static ArrayList<Salesman> getSalesmanFromFile(String filePath){
ArrayList<Salesman> salesmanList= new ArrayList<Salesman>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1]));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
String status = "Error"; //- Please review file selected. Make sure that format is followed.";
}
return salesmanList;
}
My question is, how can I set the third attribute isSelected in the method to 0 (not selected)? Since .csv file doesn't contain the tagging attribute, I'm thinking of placing it in the method above (which will be used at the start of the whole program).
I'm thinking of creating a variable within the method int isSelected = 0 but I don't know how to incorporate it with the BufferedReader. Something like:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
//int isSelected = 0;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1], isSelected?));
}
} catch (IOException ex) {
ex.printStackTrace();
}
Any help would be appreciated!

Java few errors while writing to text file?

I have a java assignment, and my last two errors are laid out in this code. For a little background, my code is taking input from a GUI and writing it into a text file. I realize you may need more code, and I will give more if needed, I just can't seem to understand these errors. Here is my code:
public void dataWriter(String data, String fileName) throws IOException
{
File file = getFileStreamPath(fileName);
if (!file.exists())
{
file.createNewFile();
}
try (FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE)) // Error "cannot find symbol, variable MODE_PRIVATE"
{
for (String string = null, data)//error "variable data is already defined in dataWriter"
{
{
writer.write(string.getBytes());
writer.flush();
}
}
}
catch (Exception e)
{
}
}
Any help is greatly appreciated. Thank you so much!
From the original question it looks as though you are trying to write out to a file. OK, something like this should work:
public void dataWriter(String data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}
The issue you were having with your above code was that the for loop syntax in Java is very different than how you originally stated.
Instead of for (String string = null, data)
An iterative for loop needs to look like this:
for (int i = 0; i < someDataStructure.size(); i++)
someDataStructure.get(i);
You could also do a for each loop if the Data Structure implements Iterable.
However, all this aside, you were attempting to iterate using a FileOutputStream when you had no List or Array over which to iterate, had you passed in another reference to a file or a list, the iteration should have looked something like this:
public void dataWriter(List data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
for (int i = 0; i < data.size(); i++)
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}

How get android cpu model name?

I want to learn my phone cpu model name and I tryed to use /proc/cpuinfo and a lot of code but I failed. Can anyone help me?
Run
$ adb shell cat /proc/cpuinfo
Here is my code
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
br.close();
String[] array = text.split(":\\s+", 2);
if (array.length >= 2) {
return array[1];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
What about your code?

Writing an array to a textfile from a textArea in java

I'm new to Java and I am trying to write what I have in a text area called AreaBooking into a textfile. I can get it to write to the textfile but just cant get them on separate lines. I may also have a lot of redundant code but I don't know as I said I'm new to this language.
I want it like
1
2
3
and not 1,2,3
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
AreaBooking.replaceSelection("");
String s[] = AreaBooking.getText().split("\n");
ArrayList<String>arrList = new ArrayList<>(Arrays.asList(s)) ;
System.out.println(arrList);
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(file_name)));
out.write(AreaBooking.getText());
out.close();
} catch (IOException ex) {
Logger.getLogger(ViewBookings.class.getName()).log(Level.SEVERE, null, ex);
}
Instead of
out.write(AreaBooking.getText());
write:
for (String s : arrList) {
out.println(s);
}
Use JTextArea#write(Writer) instead.
try (Writer writer = new BufferedWriter(new WriterReader("Inventory.txt"))) {
textArea.write(writer);
} catch (IOException exp) {
exp.printStackTrace();
}

Categories

Resources