RandomAccessFile converting int to Chinese - java

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.

Related

Reading Binary file's in JAVA

Ok so I'm learning to write and read binary file in java and this is the method I get suggested everywhere I google
Here's the weighting class
public Writer(String fileName, String text) throws IOException {
ObjectOutputStream output = null;
try{
output = new ObjectOutputStream(new FileOutputStream(fileName, true));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
} catch (IOException e) {
System.out.println("IO Exception!!");
System.exit(0);
}//THE TEXT HERE IS "test"
output.writeChars(text);
output.close();
System.out.println("Successful writing!");
}
Here's the reading Class
public Reader(String fileName) throws IOException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Not found!");
System.exit(0);
} catch (IOException e) {
System.out.println("IO Exception!!");
System.exit(0);
}
int i;
while ((i = in.read()) != -1){
System.out.print((char) i);
}
in.close();
}
but then my output is t e s t "There are squares in between each char"
For binary, non-text, files DataInputStream/DataOutputStream are more clear.
try (FileOutputStream fos = new FileOutputStream("test.bin");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF8("La projekto celas ŝtopi breĉojn en Vikipedio");
dos.writeInt(42);
dos.writeDouble(Math.PI);
}
try (FileInputStream fis = new FileInputStream("test.bin");
DataInputStream dis = new DataInputStream(fis)) {
String s = dis.readUTF8(); // "La projekto celas ŝtopi breĉojn en Vikipedio"
int n = dis.readInt(); // 42
double pi = dis.readDouble() // Math.PI
}
writeUTF8 writes a length, and the an UTF-8 encoded string. A Unicode format, so any script may be written. One may mix Japanese, Greek, emoticons and Bulgarian.

Java BufferWriter not completing write of file

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);
}
}
}

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.

Why is my program not opening my .dat file?

Hi my java program is supposed to read in and display a .txt file the user enters when prompted, convert the integers in the file to an output .dat file, then read in that .dat file and display the numbers again. When I run my program it displays the contents of the file, and creates the .dat file, but dosn't read it in again. My code is below. What do I need to do?
public class InputFile
{
public static void main(String [] args)
{
BufferedReader inputStream = null;
System.out.print("Enter file name (with .txt extension): ");
Scanner keys = new Scanner(System.in);
String inFileName = keys.next();
try
{
inputStream = new BufferedReader (new FileReader(inFileName));
System.out.println("The file " + inFileName + " contains the following lines:");
String inFileString = inputStream.readLine();
while(inFileString != null)
{
System.out.println(inFileString);
inFileString = inputStream.readLine();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println(inFileName + " not found! Try Again.");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0);
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening file.");
}
catch(IOException e)
{
System.out.println("Problem with output to the file.");
}
try
{
ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileName));
System.out.println("The file being read yields:");
int anInteger = inputStream2.readInt();
while(anInteger >= 0)
{
System.out.println(anInteger);
anInteger = inputStream2.readInt();
}
inputStream2.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem with opening the file.");
}
catch(EOFException e)
{
System.out.println("Problem reading the file.");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file.");
}
}
}
There's a mistype (or at least I suppose it was a mistype) hard to spot that makes your second loop infinite.
(...)
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0); <=====
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
Remove this ';' after the while and I guess it'll run normally.
you are not writing to the output stream because by that time the inputStream has been exhausted and is closed.
create a collection to store the elements from the first file.
String inFileName = keys.next();
Collection<String> lines = new ArrayList<String>();
...
System.out.println(inFileString);
lines.add(inFileString);
...
for(String line : lines){
...
outputStream.write(Integer.parseInt(line));
...
}

Categories

Resources