Making input command - java

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 !!! :)

Related

The content of the file when re-accessing the database is incorrect

Faced such a problem. I wrote data to a file and on the first attempt everything is written well, but subsequent ones output Null. With what it can be connected ?
public static String ExportTofile (boolean archive) throws Exception {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new Exception("Нет доступа к SDCard");}
File sdFile;
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath() + "/" + GlobalVars.DirectoryPath);
if (archive) {
sdFile = new File(sdPath +".txt");
} else
sdFile = new File(GlobalVars.AppPathData(), GlobalVars.DirectoryFileName);
Cursor cDeliveryTable;
try {
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sdFile),
"windows-1251"));
Log.d(GlobalVars.LOG_TAG, "ExpotToFile: " + sdFile.getAbsolutePath());
cDeliveryTable = GlobalVars.db.rawQuery("select * from CustDeliveryTable order by _id", null);
cDeliveryTable.moveToFirst();
while (!cDeliveryTable.isAfterLast()) {
CustDeliveryTable st = new CustDeliveryTable(cDeliveryTable.getLong(cDeliveryTable.getColumnIndex("_id")));
br.write(st.CargoStr() + "\r\n");
cDeliveryTable.moveToNext();}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;}
return sdFile.getAbsolutePath();}
public String CargoStr() {
String sLine;
sLine = this.Name
+ ";"
+ this.Address
+ ";"
+ this.Number
+ ";";
return sLine.substring(0, sLine.length() - 1);}
First write to file
Subsequent entries

I can't write data on a new line in a file

Whatever I did, I did not write a new data on a new line in the file.
How can I fix it?
For example mary's score is 100 and smith's score is 150, but in the txt file it is
mary 100smith 150
I wanna smith 150 in a new line
public class HighScores {
public HighScores(){
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try{
Checker = new File("highScores.txt");
if(!Checker.exists()){
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while(sc.hasNextLine()){
txt = txt.concat(sc.nextLine()+"\n");
}
String score=String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt.concat(name + " "+ score +"\n");
pw = new PrintWriter(Checker);// writing the checker
pw.write(txt +"\r\n");
pw.println() gives the same problem too.
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
sc.close();
pw.close();
}
}
}
The code is dodgy, but should actually do what you expect of it.
You are probably viewing the resulting file with a Windows notepad app. It expects "\r\n" as a newline separator, as do most other Windows apps.
Use the following code
public class HighScores {
public HighScores() {
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try {
Checker = new File("highScores.txt");
if (!Checker.exists()) {
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while (sc.hasNextLine()) {
txt = txt.concat(sc.nextLine() + "\n");
}
String score = String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt + name + " " + score;
pw = new PrintWriter(Checker);// writing the checker
pw.println(txt);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
sc.close();
pw.close();
}
}
}

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

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