How to close threads in Java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
Write 100 positive and 100 negative random integers alternately to the numbers file, listing them separated by a space. Then read this file and scatter the read numbers into 2 files: positive_numbers and negative_numbers, with positive and negative numbers, respectively.
Three files are created. The numbers file contains both positive and negative numbers. In the numers_positive file, only positive ones are present (as they should be). And the file numers_negative is empty. I think it's about closing threads, but I can't figure out how to close them correctly.
public class IO {
public static void main(String[] args) {
FileWriter fw = null;
FileWriter fw1 = null;
File file = new File("D:/numbers.txt");
FileWriter fwnp;
FileWriter fwnn;
for (int i = 0; i < 101; i++) {
try {
fw = new FileWriter(file, true);
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
FileReader fr = new FileReader("D:/numbers.txt");
fwnp = new FileWriter("D:/numbers_positive.txt");
int c = fr.read();
while (c > 0) {
fwnp.write(c);
c = fr.read();
fwnp.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 101; i++) {
try {
fw1 = new FileWriter(file, true);
fw1.write(" " + getRandomNumber(-100, -1));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw1 != null)
fw1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
FileReader fr = new FileReader("D:/numbers.txt");
fwnn = new FileWriter("D:/numbers_negative.txt");
int c = fr.read();
while (c < 0) {
fwnn.write(c);
c = fr.read();
fwnn.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static int getRandomNumber(int a, int b) {
if (b < a)
return getRandomNumber(b, a);
return a + (int) ((1 + b - a) * Math.random());
}
}

As noted:
You are not using threads, so this it not about threads.
You don't "close" threads. Threads are not closable.
You do need to close input/output streams ... and you are not doing that in all of places you need to in your program.
But the modern way to close a stream doesn't involve finally. Way back in Java 7, they introduced the try with resources syntax which will automatically close resources for you. For example:
try {
fw = new FileWriter(file, true);
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
can be written as
try (fw = new FileWriter(file, true)) {
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
}
Note that fw will be auto-closed. It is better to make fw a local declaration so that it is out of scope after the statement:
try (FileWriter fw = new FileWriter(file, true)) {
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
}
// fw is out of scope.
Also, you don't need to call flush after each write when you are writing to a file. Any buffered output is written when the output stream / writer is closed. You just need to make sure that the stream / writer is always closed.

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

Reading and writing arraylist to textfile

I'm having a problem with reading and writing arraylist to a text file. Specifically with reading. What I'm trying to do is read from a text file and transfer it to an array list. After which i would edit the list and write it back to the text file. I think I go the writing done but not the reading. I've tried reading several similar questions here but cant seem to inject it into my code.
Reading code
public void read(List<AddressBook> addToList){
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
} }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Here's what I've done with the write
public void write(List<AddressBook> addToList) {
try {
File file = new File("bank_account.csv"); //file
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//FileWriter fw = new FileWriter(file.getAbsoluteFile());
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
for (AddressBook write : addToList) {
bw.write(write.getName() + "," + write.getAddress() + "," + write.getTelNum() + "," + write.getEmailAdd());
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
}
}
I bet in there you will need to do something like:
reading each line
parsing it (each line is a CSV)
creating a new AddressBook object with all that info
add it to the collection
The code for that will look like:
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
String[] splitted = currentLine.split(",");
AddressBook address = new AddressBook(splitted[0], splitted[1], splitted[2], splitted[3]);
addToList.add(address);
}
Of course there are things you will need to check and validate, but that is roughtly it.
Maybe you need read method like this.
public void read() {
List<AddressBook> addToList =new ArrayList<AddressBook>();
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
// for (AddressBook read : addToList) {
String[] split =currentLine.split(",");
AddressBook read = new AddressBook();
read.setName(split[0]);
read.setAddress(split[1]);
read.setTelNum(split[2]);
read.setEmailAdd(split[3]);
// br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
// }
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

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

Why won't the catch block run?

I have the following method to write an array to a text file. If a existing text file is given then it works fine but if a file that doesn't exist is given neither try-catch will run the code to restart the method. I'm not given any error or anything but the catch block won't run. I didn't think i would need to catch for an IOException but the code won't even run if i don't do that. So yea, anyone know how i can get this to work?
Edit: Forgot to mention the getInput method prompts the user for input.
private static void openFileWriter(String prompt, boolean append, int wordsperline, String[] story) {
try {
try {
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length-1; x++) {
if (story[x] == null) {
} else {
if (wordsperline == 21) {
save.println(story[x]);
wordsperline = 0;
} else {
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
} catch (FileNotFoundException e1) {
openFileWriter("File not found", append,wordsperline,story);
}
} catch (IOException e) {
// TODO Auto-generated catch block
openFileWriter("File not found", append,wordsperline,story);
}
}
If the File does not exist you cannot write to it, in your catch block you are trying to write the error to the File that doesn't exist. Also, I think you only need 1 catch block here, and note that one of the if statement blocks is empty.
try this:
try
{
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for(int x = 0; x <= story.length-1; x++)
{
if (story[x] == null)
{
}
else
{
if (wordsperline == 21)
{
save.println(story[x]);
wordsperline = 0;
}
else
{
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1.getMessage());
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
See FileWriter javadoc.
Quoting from the constructor doc:
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you pass it a filename that doesn't exist, but is a legal filename in a location where you have permission to write, it simply creates the file.
Your code in fact does reach the catch blocks if you pass it a directory (somewhat oddly, it catches a FileNotFoundException in this situation for me rather than the documented IOException).
To check if a file exists, see File javadoc
Try this version and send the stack trace when you get the exception:
public static List<String> splitByLength(String filename, int length) {
List<String> splitWords = new ArrayList<String>();
for (int i = 0; i < str.length(); i += length) {
splitWords
.add(str.substring(i, Math.min(str.length(), i + length)));
}
return splitWords;
}
private static void openFileWriter(String prompt, boolean append,
int wordsperline, String[] story) {
PrintWriter save = null;
try {
save = new PrintWriter(new FileWriter("c:\\test.txt", append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length - 1; x++) {
if (story[x] != null) {
List<String> splitWords = splitByLength(story[x], 21);
for (String line : splitWords) {
save.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (save != null) {
save.close();
}
}
}

Categories

Resources