Java BufferWriter not completing write of file - java

Here is my situation. I am writing <!ENTITY> declarations to an XML file. I read in the original XML file using a Scanner. As the scanner reads the input file i write the lines out to the BufferedWriter. When the scanner is on line 2 i write my <!ENTITY> values from an ArrayList that was passed to the method. My <!ENTITY> values write no problem. Issue I am having is that I am only getting 400 or so lines of the file written to the output file.
I've read through a few posts on here regarding BufferedWriters not completing writes to files, and all seemed to point to ensuring the writer is closed. I have closed my writer object.
private void addEntityRefs(Map<String, String> icns, File xml)
{
String path = xml.getAbsolutePath().substring(0,xml.getAbsolutePath().lastIndexOf(File.separator)+1);
ArrayList<String> list = new ArrayList<String>();
Scanner reader = null;
BufferedWriter writer = null;
for(Map.Entry<String, String> e : icns.entrySet())
{
list.add(e.getValue());
}
try
{
reader = new Scanner(xml);
//standardOut.println("Reading " + xml.getName());
//System.out.println();
int c = 0;
String output = path + "out2.xml";
writer = new BufferedWriter(new FileWriter(new File(output)));
while(reader.hasNextLine())
{
c++;
if(c == 1)
{
writer.append(reader.nextLine().replaceAll("\\s", " "));
}
else if(c == 2)
{
System.out.println("writing entities # line 2");
writer.append("\n<!DOCTYPE pm [\n");
for(int i = 0; i < list.size(); i++)
{
writer.append("<!ENTITY " + list.get(i).trim() + " SYSTEM \"" + list.get(i).trim() + ".cgm\" NDATA cgm>\n");
}
writer.append("<!NOTATION cgm PUBLIC \"cgm\" \"\">\n]>\n");
}
else
{
System.out.println("Writing line " + c);
writer.append(reader.nextLine().replaceAll("\\s", " ")+ "\r");
}
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, ex);
JOptionPane.showMessageDialog(this, ex, "File Not Found Exception", JOptionPane.ERROR_MESSAGE);
}
catch (IOException ex)
{
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, ex);
JOptionPane.showMessageDialog(this, ex, "IO Exception", JOptionPane.ERROR_MESSAGE);
}
finally
{
try
{
reader.close();
writer.close();
}
catch(Exception e)
{
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, e);
JOptionPane.showMessageDialog(this, e, "Exception", JOptionPane.ERROR_MESSAGE);
}
}
}
The output of the writer is used to generate PDFs. The file being read and <!ENTITY> declarations added to is about 26,000 lines long. Can someone point me to where I have gone wrong? This method works without issue when I run the application from NetBeans, but once I build it and attempt to run from the JAR file is when it stops after about 400 lines.

When it stops at certain line. do you see the file getting created with those lines? could be that buffer is been flushed at that moment and failed in that operation.
You does not move the pointer to the next line when c == 2 but continue to write in in next iteration.
It is always better to use the charset when reading/writing.
try flushing at the end.
and closing both reader and writer in-dependently.
needless use of ArrayList.
i did minor changes to this one. see if it still works.
private void addEntityRefs(Map<String, String> icns, File xml) {
Scanner reader = null;
BufferedWriter writer = null;
try {
reader = new Scanner(xml, "utf-8");
// standardOut.println("Reading " + xml.getName());
// System.out.println();
int count = 0;
File targetFile = new File(xml.getParentFile(), "out2.xml");
if (!targetFile.exists()) {
boolean created = targetFile.createNewFile();
System.out.println("File created: " + created);
}
writer = new BufferedWriter(new FileWriter(targetFile));
while (reader.hasNextLine()) {
count++;
if (count == 1) {
writer.append(reader.nextLine().replaceAll("\\s", " "));
} else if (count == 2) {
System.out.println("writing entities # line 2");
writer.append("\n<!DOCTYPE pm [\n");
for (String item : icns.keySet()) {
item = item.trim();
writer.append("<!ENTITY " + item + " SYSTEM \"" + item + ".cgm\" NDATA cgm>\n");
}
writer.append("<!NOTATION cgm PUBLIC \"cgm\" \"\">\n]>\n");
} else {
System.out.println("Writing line " + count);
writer.append(reader.nextLine().replaceAll("\\s", " ")).append("\r");
}
}
// done writing
writer.flush();
} catch (FileNotFoundException ex) {
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, ex);
JOptionPane.showMessageDialog(this, ex, "File Not Found Exception", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, ex);
JOptionPane.showMessageDialog(this, ex, "IO Exception", JOptionPane.ERROR_MESSAGE);
} finally {
try {
reader.close();
} catch (Exception e) {
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, e);
JOptionPane.showMessageDialog(this, e, "Exception", JOptionPane.ERROR_MESSAGE);
}
try {
writer.close();
} catch (Exception e) {
Logger.getLogger(AARPdfGenUI.class.getName()).log(Level.WARN, null, e);
JOptionPane.showMessageDialog(this, e, "Exception", JOptionPane.ERROR_MESSAGE);
}
}
}

Related

RandomAccessFile converting int to Chinese

I am trying to read some book objects that I have stored in a txt file. When I run the code it runs but returns incorrect information.
Expected result:
Book isbn=225346873945, price=12.99, yearPublished=2015, title='Finders Fee'
Actual result:
Book isbn=⸹㔬⁹敡牐畢汩獨敤㴲〱〬⁴, price=9.770698273454668E199, yearPublished=1633907817, title='捥映瑨攠坩汤❽਀䵂潯死楳扮㴲㈵㌴㘸㜳㤴㔬⁰物捥㴱㈮㤹Ⱐ祥慲'
The information in the txt file is correct but when it is displayed in the console it is incorrect. Ignoring the invalid while loop, how can I fix this code?
try {
bookFile.seek(0);
for (Book bookObj : bookList) {
String tempBook = bookObj.toString();
bookFile.writeBytes(tempBook);
bookFile.writeBytes(System.getProperty("line.separator"));
}
} catch (IOException e) {
System.out.println("Error writing to " + BOOK_LIST_FILE);
} catch (Exception e) {
System.out.println("Generic error" + e);
}
try{
Book tempBook = new Book();
bookFile.seek(0);
while (true) {
readData(bookFile, tempBook);
System.out.println(tempBook.toString());
}
} catch (IOException e){
System.out.println("IO Error " + e);
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
}
public static void readData( RandomAccessFile bookFile, Book book) throws IOException, EOFException, Exception
{
StringBuffer sb = new StringBuffer();
for (int i=0; i<book.getISBN_LENGTH(); i++){
sb.append(bookFile.readChar());
}
book.setIsbn(sb.toString());
book.setPrice(bookFile.readDouble());
book.setYearPublished(bookFile.readInt());
sb.setLength(0);
for (int i = 0; i <book.TITLE_LENGTH ; i++) {
sb.append(bookFile.readChar());
}
book.setTitle(sb.toString());
}
readInt() and friends are for binary data. Your file is text. You should just read bytes from this file. RandomAccessFile is a poor choice: use BufferedReader over an InputStreamReader over a FileInputStream, and the readLine() method.

in this example, what is the third missing possibility for the try block?

public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: "
+ e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
}
else {
System.out.println("PrintWriter not open");
}
}
}
This method's try block has three different exit possibilities; here are two of them.
1) Code in the try statement fails and throws an exception. This could be an IOException caused by the new FileWriter statement or an IndexOutOfBoundsException caused by a wrong index value in the for loop.
2) Everything succeeds and the try statement exits normally.
Could someone tell me, what is the third potential possibility that could happen but is not mentioned here?
The exception can be propagated to the next method in the stack

Making input command

I have a little problem with making a java command for program i have some code but i do not know how to continue i stuck in one place BTW the command i want to make is /sendcash [username] [money] // how it looks like
I have this code:
if (cmd.equals(AdminCommands[1])) {
String player = scanner.next();
int money = scanner.nextInt();
File folder = new File(player);
File pFile = new File(folder, player + ".txt");
File bFile = new File(folder, money + ".txt");
if (pFile.exists() && bFile.exists()) {
try {
Account pAcc = new Account(player, money);
if(pAcc.admin != 1) {
try {
writer = new BufferedWriter(new FileWriter(bFile));
writer.write(player);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
LabelInfo.setText("Money transfer complited ! ( " + money + " ) to ( " + pAcc.name + " )");
} else {
LabelInfo.setText("You can't transfer money to an admin!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Username doesn't exist!");
}
}
}
EDIT Now with this code nothing happening in the console and in the files too i dont know what to do here is the code in the class Account
public Account(String player, int cash) {
this.username = player;
this.money = cash;
}
If you mean by transfer the money to write the result into files, you can do it like this:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(pFile));
writer.write(player);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
Problem solved i actually have missed something in the constructor class Account and also can somebody explain me why with the brackets in writer.write(""+cashTransfer); are not showing the characters like ✐, 蚠, etc.. for example when i will put in [cash] field 100 its shows me the letter d and so on ...
Here is the whole working code...
if (cmd.equals(AdminCommands[1])) {
String playerUsername = scanner.next();
int cashTransfer = scanner.nextInt();
File folder = new File(playerUsername);
File pFile = new File(folder, playerUsername + ".txt");
File bFile = new File(folder, "balance.txt");
if (pFile.exists()) {
try {
Account pAcc = new Account(playerUsername, cashTransfer);
FileWriter bWriter = new FileWriter(bFile);
BufferedWriter writer;
writer = new BufferedWriter(bWriter);
writer.write(""+cashTransfer);
pAcc.SaveInfo();
writer.close();
LabelInfo.setText("Money transfer complited ! ( $" + cashTransfer + " ) to ( " + pAcc.username + " )");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "ERROR: Can't save balance !");
}
} else {
LabelInfo.setText("Player not found !");
}
}
BTW Thank you #Salah for helping me !!! :)

Stream closed Exception while adding for 2nd time

I am trying to index documents using Lucene... However I am getting a StreamClosed exception..
I think it is related more to Java then Lucene....
Can someone please guide..
The code snippet is as follows:
static void indexDocs(File file,boolean flag,Directory dir,IndexWriterConfig iwc)
throws IOException {
// do not try to index files that cannot be read
FileInputStream fis = null;
if (file.canRead()) {
if (file.isDirectory())
{
String[] files = file.list();
System.out.println("list " + files.length);
if (files != null) {
for (int i = 0; i < files.length; i++) {
System.out.println("Invoked for " + i + "and " + files[i]);
indexDocs(new File(file, files[i]),flag,dir,iwc);
}
}
}
else {
boolean flags=true;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
try {
Document doc = new Document();
LineNumberReader lnr=new LineNumberReader(new FileReader(file));
Field pathField = new StringField("path", file.getPath(), Field.Store.YES);
doc.add(pathField);
String line=null;
int i=0;
doc.add(new StringField("TT",file.getName(),Field.Store.YES));
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
doc.add(new TextField("DD", br));
System.out.println("Looping Again");
while(flags)
{
IndexWriter iwcTemp1=new IndexWriter(dir,iwc);
while( null != (line = lnr.readLine()) ){
i++;
StringField sf=new StringField("EEE",line.trim(),Field.Store.YES);
doc.add(sf);
if(i%10000==0)
{
System.out.println("Breaking " + i);
lnr.mark(i);
break;
}
sf=null;
}
if(line==null)
{
System.out.println("FALSE " );
flags=false;
}
System.out.println("FILE NAME IS FTP " + file.getName());
if (iwcTemp1.getConfig().getOpenMode() == OpenMode.CREATE_OR_APPEND) {
try
{
iwcTemp1.addDocument(doc);
iwcTemp1.commit();
iwcTemp1.close();
}catch(Throwable t)
{
lnr.close();
br.close();
fis.close();
t.printStackTrace();
}
} else {
try
{
System.out.println("updating " + file);
iwcTemp1.updateDocument(new Term("path", file.getPath()), doc);
}catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("END OF WHILE");
lnr.reset();
}//end of While
}catch (Exception e) {
e.printStackTrace();
}finally {
fis.close();
}
}
}
}
Exception I am getting is on the line where I am adding Document to Writer...
Exception trace:
java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:114)
at java.io.BufferedReader.read(BufferedReader.java:270)
at org.apache.lucene.analysis.standard.StandardTokenizerImpl.zzRefill(StandardTokenizerImpl.java:923)
at org.apache.lucene.analysis.standard.StandardTokenizerImpl.getNextToken(StandardTokenizerImpl.java:1133)
at org.apache.lucene.analysis.standard.StandardTokenizer.incrementToken(StandardTokenizer.java:171)
at org.apache.lucene.analysis.standard.StandardFilter.incrementToken(StandardFilter.java:49)
at org.apache.lucene.index.DocInverterPerField.processFields(DocInverterPerField.java:102)
at org.apache.lucene.index.DocFieldProcessor.processDocument(DocFieldProcessor.java:245)
at org.apache.lucene.index.DocumentsWriterPerThread.updateDocument(DocumentsWriterPerThread.java:265)
at org.apache.lucene.index.DocumentsWriter.updateDocument(DocumentsWriter.java:432)
at org.apache.lucene.index.IndexWriter.updateDocument(IndexWriter.java:1513)
at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1188)
at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1169)
at com.rancore.MainClass2.indexDocs(MainClass2.java:236)
Can someone please guide...Where am I going wrong...Kindly guide...
Your exception handling is incorrectly structured. It shouldn't be possible to continue with the read code if new FileInputStream() throws an exception.

JAVA printwriter increase buffer size from 8192 bytes

I'm trying to create a file that maps every possible binary combination of some part of speech tags, and for some reason the java program I've written just stops after 8192 bytes. I assume that this is the maximum buffer size or something? How can I change that?
My code:
try {
Scanner in = new Scanner(new FileInputStream(file.getPath()));
PrintWriter out = new PrintWriter(new FileOutputStream("S2.gr"));
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
private static void createS2(Scanner in, PrintWriter out) {
String[] pos = in.useDelimiter("\\A").next().split("\\n");
out.println("1\tS2");
for (String x : pos) {
out.println("1\tS2\t_" + x);
}
for (String x : pos) {
String temp = ("1\t_" + x + "\t" + x);
out.println(temp);
for (String y : pos) {
out.println(temp + " _" + y);
}
}
for (String x : pos) {
System.out.println(x);
}
}
Try this...
Scanner in = null;
PrintWriter out = null;
try {
in = new Scanner(new FileInputStream(file.getPath()));
out = new PrintWriter(new FileOutputStream("S2.gr"));
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
finally {
if(in != null) in.close();
if(out != null) out.close();
}
Note: if you're using Java 7, there's a new feature to make this easier. e.g.
try (Scanner in = new Scanner(new FileInputStream(file.getPath()));
PrintWriter out = new PrintWriter(new FileOutputStream("S2.gr")))
{
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
Note: I don't have a JDK 7 available to me at the moment, so the second example might not be 100% correct, but the idea is that the new language feature can manage closing resources for you.

Categories

Resources