Unable to print console output in same format onto text document - java

I have my java file set up to calculate a phone bill and print out to the console in this format.
Invoice
--------------------------
Account Amount Due
10011 $12.25
10033 $11.70
--------------------------
Total $23.95
but when I run the program I only get this on the text file
Account Amount_Due
10011 $12.25
10033 $11.7
Can someone help me edit my filecreating code in correct format?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
public class PhoneBill {
Vector data;
Vector processed = new Vector();
Vector markProcessed = new Vector();
public void readFile(String inFileStr)
{
String str = "";
data = new Vector<LineItem>();
FileReader fReader;
InputStream inFileStream;
try{
fReader = new FileReader(inFileStr);
BufferedReader br=new BufferedReader(fReader);
String line;
while ((line=br.readLine())!= null){
if (line.indexOf("_") != -1)
continue;
else
if (!line.isEmpty()){
data.add(new LineItem(line.trim()));
}
}
br.close();
}
catch (Exception e){
}
}
public void processCharges()
{
String out = "Account Amount_Due\n";
System.out.println ("Invoice");
System.out.println ("--------------------------");
System.out.println ("Account " + "Amount Due ");
double total = 0.0;
double lCharges =0;
boolean done = false;
DecimalFormat numFormatter = new DecimalFormat("$##.##");
for (int j = 0; j < data.size(); j++ ){
LineItem li = (LineItem)data.get(j);
String accNum = li.getAccountNum();
if (j > 0){
done = checkProcessed(accNum);}
else
processed.add(accNum);
if (!done){
lCharges = 0;
for (int i = 0; i < data.size(); i++){
String acc = ((LineItem)data.get(i)).getAccountNum();
if (acc.equals(accNum) && !done)
lCharges += processItemCharges(accNum);
done = checkProcessed(accNum);
}
lCharges+=10.0;
System.out.format ("%s" + " $%.2f%n",accNum, lCharges);
out += accNum+" ";
out += numFormatter.format(lCharges)+"\n";
processed.add(accNum);
total += lCharges;
}
}
System.out.println ("--------------------------");
System.out.format ("%s" + " $%.2f%n","Total", total);
writeToFile("invoice.txt", out);
}
private void writeToFile(String filename,String outStr)
{
try{
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe){
System.out.println(ioe.getMessage());
}
}
private boolean checkProcessed(String accNum){
if (processed.contains(accNum))
return true;
else
return false;
}
private double processItemCharges(String accNum)
{
double charges = 0.0;
for (int i = 0; i < data.size(); i++)
{
if(((LineItem)data.get(i)).getAccountNum().equals(accNum))
charges += ((LineItem)data.get(i)).getCharges();
}
return charges;
}
public static void main(String[] args)
{
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
class LineItem{
String accNum ;
String timeOfCall;
double mins;
double amountDue;
boolean counted = false;
public LineItem(String accStr)
{
processAccount(accStr);
}
private void processAccount(String accStr){
StringTokenizer st = new StringTokenizer(accStr);
accNum = (String)st.nextElement();
timeOfCall = (String) st.nextElement();
mins = Double.parseDouble((String) st.nextElement());
if (timeOfCall.compareTo("08:00")>0 && timeOfCall.compareTo("22:00")<0)
amountDue = mins*0.10;
else
amountDue = mins*0.05;
}
public String getAccountNum()
{
return accNum;
}
public double getCharges()
{
return amountDue;
}
}
}

Study this. It uses a bit more advanced Java but understanding it will be well worth your while.
package test;
import java.io.*;
import java.util.*;
public class PhoneBill {
private static String BILL_FORMAT = "%-10s $%,6.2f\n";
private static boolean DEBUG=true;
Map<String, List<LineItem>> accounts = new HashMap<String,List<LineItem>>();
public void readFile(String inFileStr) {
FileReader fReader=null;
try {
fReader = new FileReader(inFileStr);
BufferedReader br = new BufferedReader(fReader);
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("_") != -1)
continue;
else if (!line.isEmpty()) {
LineItem li = new LineItem(line.trim());
List<LineItem> list = accounts.get(li.accNum);
if(list==null){
list = new ArrayList<LineItem>();
accounts.put(li.accNum, list);
}
list.add(li);
}
}
br.close();
} catch (Exception e) {
/* Don't just swallow Exceptions. */
e.printStackTrace();
} finally {
if(fReader!=null){
try{
fReader.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}
public void processCharges() {
StringBuffer out = new StringBuffer(100)
.append("Invoice\n")
.append("--------------------------\n")
.append("Account Amount Due \n");
double total = 0.0;
double lCharges = 0;
for (String accNum:accounts.keySet()) {
List<LineItem> account = accounts.get(accNum);
lCharges = 10;
for(LineItem li:account){
lCharges += li.getCharges();
}
total += lCharges;
out.append(String.format(BILL_FORMAT, accNum, lCharges));
}
out.append("--------------------------\n");
out.append(String.format(BILL_FORMAT, "Total", total));
writeToFile("invoice.txt", out.toString());
}
private void writeToFile(String filename, String outStr) {
if(DEBUG){
System.out.printf("========%swriteToFile:%s=========\n", '=', filename);
System.out.println(outStr);
System.out.printf("========%swriteToFile:%s=========\n", '/', filename);
}
try {
File file = new File(filename);
// If file doesn't exist, then create it.
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args) {
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
static class LineItem {
String accNum;
double timeOfCall;
double mins;
double amountDue;
boolean counted = false;
private static final double EIGHT_AM = convertTime("08:00");
private static final double TEN_PM = convertTime("22:00");
public LineItem(String accStr) {
processAccount(accStr);
}
private void processAccount(String accStr) {
StringTokenizer st = new StringTokenizer(accStr);
accNum = st.nextToken();
timeOfCall = convertTime(st.nextToken());
mins = Double.parseDouble(st.nextToken());
if (timeOfCall > EIGHT_AM && timeOfCall < TEN_PM)
amountDue = mins * 0.10;
else
amountDue = mins * 0.05;
}
public String getAccountNum() {
return accNum;
}
public double getCharges() {
return amountDue;
}
private static double convertTime(String in){
/* Will blow up if `in` isn't given in h:m. */
String[] h_m = in.split(":");
return Double.parseDouble(h_m[0])*60+Double.parseDouble(h_m[1]);
}
}
}

Printing to the console (i.e. System.out.println) is not the same as concatenating to your out variable (i.e. out+=).
So when you call
writeToFile("invoice.txt", out);
You are only writing what is in the string 'out' to the file. If you look back at your code, you'll see that all of your missing lines are only ever printed to the console, but not concatenated to the 'out' variable. Correct that and you shouldn't have a problem.

Related

Method cannot get updated value from a varible

I am trying to count number of words from three text files respectively. Three classes are running in multi-threads. In each thread, sum of the counted words will be passed to a class counter and update to sum all counts to the counter after all threads are completed.
I meet two problem that the "totalWordCount" can be updated by the class setter. But it cannot be gotten by a getter in the same class. Other problem is that I cannot check the Readfiles threads alive.
I have searched on internet & shoot many times but cannot solve, any comment are welcome, thanks a lot!
NumberWords class:
public class NumberWords {
private int activeThread;
private int totalWordCount;
private String getThreadName;
public NumberWords(int activeThread) {
this.activeThread = activeThread;
}
public synchronized void incTotalWordCount(int n) {
totalWordCount += n;
System.out.println("The total word count is " + totalWordCount);
}
public synchronized void printCount() {
System.out.println("The total word count(print count) is " + totalWordCount);
}
public synchronized void decActiveThread() {
getThreadName = Thread.currentThread().getName();
System.out.println(getThreadName);
if (Thread.getAllStackTraces().keySet().size() != 0) {
// Get number of active threads
activeThread = Thread.getAllStackTraces().keySet().size();
activeThread--;
if (activeThread == 0) {
System.out.println("The total number of word in the three files is " + totalWordCount);
System.out.println("The active threads is/are " + activeThread);
}
}
}
}
Read file and count number of words:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
public class ReadFile1 extends Thread implements Runnable {
private NumberWords nw;
public ReadFile1(NumberWords nw) {
this.nw = nw;
}
//set file path
String path1 = System.getProperty("user.dir") + File.separator + "text1.txt";
BufferedReader br1 = null;
public void run() {
try {
br1 = new BufferedReader(new FileReader(path1));
String contentLine = br1.readLine();
while (contentLine != null) {
// Count number of words
String[] parts = contentLine.split(" ");
int count = 0;
for (int i = 0; i < parts.length; i++) {
count++;
}
// Check number of words counted.
System.out.println("The number of words in file(text1.txt) is " + count);
//Pass words count to sum
nw.incTotalWordCount(count);
contentLine = br1.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (br1 != null) {
br1.close();
}
} catch (IOException ioe) {
System.out.println("Error in closing the BufferedReader");
}
}
}
}
Main class:
public class TestReadFile {
public static void main(String args[]){
NumberWords nw = new NumberWords(args.length);
Thread rf1 = new Thread(new ReadFile1(nw));
Thread rf2 = new Thread(new ReadFile2(nw));
Thread rf3 = new Thread(new ReadFile3(nw));
rf1.start();
rf2.start();
rf3.start();
//Get total word cont
nw.decActiveThread();
}
}
How about this:
public class NumberWords {
private int totalWordCount;
private int activeThreads;
public synchronized void incTotalWordCount(int n) {
totalWordCount += n;
activeThreads--;
System.out.println("The total word count is " + totalWordCount);
}
public synchronized void printCount() {
System.out.println("The total word count(print count) is " + totalWordCount);
}
public int getActiveThreads() {
return activeThreads;
}
public void setActiveThreads(int activeThreads) {
this.activeThreads = activeThreads;
}
}
ReadFile:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadFile implements Runnable {
private NumberWords nw;
private Path filePath;
public ReadFile(NumberWords nw, Path filePath) {
this.nw = nw;
this.filePath = filePath;
}
BufferedReader br1 = null;
public void run() {
try {
int count = 0;
for (String line : Files.readAllLines(filePath)) {
String[] parts = line.split(" ");
for (String w : parts) {
count++;
}
}
nw.incTotalWordCount(count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Main:
import java.io.File;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String args[]) throws InterruptedException {
NumberWords nw = new NumberWords();
ExecutorService execSvc = Executors.newCachedThreadPool();
new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text1.txt"))).start();
new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text2.txt"))).start();
new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text3.txt"))).start();
nw.setActiveThreads(3);
while (nw.getActiveThreads() > 0) {
Thread.sleep(100);
System.out.println("Waiting for Tasks to complete!");
}
nw.printCount();
}
}

How to close one window using Control D/Z without exiting the whole program (multithreaded java socket)

Screenshot of program running (top left: server, the rest are clients):
In the bottom-right window, I am trying to press Control D (mac) (for windows it's control Z) in order to exit the bottom right window/client alone without exiting the entire application/program but it doesn't seem to be working because I can still type "it didn't work" and it outputs the message.
My question is: What changes can I make to the following code so that when a client presses Control D it will close just one window/client and not exit the whole application?
Part of code that should close the window (currently empty):
//This is the code that prints messages to all clients
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals(null) && !line.equals("null") && !line.equals(null) && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
if(!line.equals("") == true && line.isEmpty()== false)
{
threads[i].os.println(name + ": " + line);
}
}
//After Control D/Z is pressed, this code will execute
else if(line.equals(null) || line.equals("null") || line.contains("null"))
{
try
{
//This code location exits the program, system.exit(0) and system.exit(-1) didn't work
//how do i close only one client window here without exiting the whole program?
}
catch (NullPointerException ignored)
{
}
finally
{
}
// threads[i].os.close();
// System.exit(0);
}
}
}
NOTE: SKIP THE REST and scroll down if you already know the answer
Full code of ClientThreads.java:
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.nio.*;
import java.nio.channels.FileChannel;
class ClientThreads extends Thread
{
public String path = "";
public String name1 = "";
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final ClientThreads[] threads;
private int maxClientsCount;
public int position = 0;
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public String[] namesList = new String[10];
public ClientThreads(Socket clientSocket, ClientThreads[] threads,
String name, String[] namesList, List<String> listName)
{
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.name1 = name;
this.namesList = namesList;
}
#SuppressWarnings("deprecation")
public void run()
{
int maxClientsCount = this.maxClientsCount;
ClientThreads[] threads = this.threads;
synchronized (listName)
{
//Iterator i = listName.iterator(); // Must be in synchronized block
ListIterator<String> i = listName.listIterator();
}
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
String name3;
while (true)
{
//os.println("What is your name?");
name = is.readLine().trim();
name3 = name;
break;
}
synchronized(listName)
{
if(!listName.contains(name))
{
if(!listName.contains(name) && name != null && !name.isEmpty())
{
listName.add(name);
Path currentRelativePath = Paths.get("");
path = currentRelativePath.toAbsolutePath().toString();
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] == this)
{
clientName = "#" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null)
{
}
}
}
while (true)
{
synchronized(listName)
{
}
String line = is.readLine();
if (line.contains("3582938758912781739713asfaiwef;owjouruuzlxjcjnbbiewruwoerpqKFDJiuxo9"))
{
break;
}
else
{
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals(null) && !line.equals("null") && !line.equals(null) && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
if(!line.equals("") == true && line.isEmpty()== false)
{
threads[i].os.println(name + ": " + line);
}
}
else if(line.equals(null) || line.equals("null") || line.contains("null"))
{
try
{
//This code location exits the program, system.exit(0) and system.exit(-1) didn't work
//how do i close only one client window here without exiting the whole program?
}
catch (NullPointerException ignored)
{
}
finally
{
}
// threads[i].os.close();
// System.exit(0);
}
}
}
// }
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] != this && threads[i].clientName != null)
{
// threads[i].os.println(name + "has disconnected.");
threads[i].listName.remove(name);
listName.remove(name);
// threads[i].os.println("The list now contains: " + listName);
// System.out.println("A user disconnected. The list now contains: " +listName);
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] == this)
{
//threads[i] = null;
}
}
}
// is.close();
// os.close();
//clientSocket.close();
}
catch (IOException e)
{
}
}
}
Full code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ChatClient implements Runnable
{
public static String path = "";
private static Socket clientSocket = null;
private static PrintStream os = null;
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static String[] namesList = new String[10];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public ChatClient()
{
}
public static void main(String[] args)
{
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
// System.out.println("args[0] is: " + args[0]);
int portNumber = Integer.valueOf(args[0]);
String host = "localhost";
//int filePort = Integer.valueOf(args[0]);
try
{
synchronized(listName)
{
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
}
catch (UnknownHostException e)
{
//System.err.println("Don't know about host " + host);
} catch (IOException e)
{
// System.err.println("Couldn't get I/O for the connection to the host "
// + host);
}
if (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new ChatClient()).start();
while (!closed)
{
os.println(inputLine.readLine() );
}
// os.close();
//is.close();
//clientSocket.close();
}
catch (IOException e)
{
// System.err.println("IOException: " + e);
}
}
}
#SuppressWarnings("deprecation")
public void run()
{
String responseLine = "";
try
{
while ((responseLine = is.readLine()) != null)
{
if(responseLine!=null && !responseLine.equals(null) && responseLine!="null" && !responseLine.equals("null") && !responseLine.contains("null"))
{
System.out.println(responseLine);
}
else if(responseLine.contains("null") || responseLine.equals("null") || responseLine==null || responseLine.equals(null))
{
//This is another location which will be executed if Control D/Control Z is pressed
//os.close();
// is.close();
//System.exit(0);
}
}
//closed = true;
}
catch (IOException e)
{
// System.err.println("IOException: " + e);
}
}
}
Full code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static List<String> listName = Collections.synchronizedList(new ArrayList<String>());
List<String> l = Collections.synchronizedList(new ArrayList<String>());
public static ServerSocket serverSocket = null;
public static Socket clientSocket = null;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static String[] namesList = new String[10];
// public ChatClient arrayOfNames = new ChatClient;
public static void main(String args[])
{
synchronized (listName)
{
//Iterator i = listName.iterator(); // Must be in synchronized block
Iterator<String> i = listName.listIterator();
}
int once = 0;
if(once == 0)
{
// System.out.println("args[0] is: " + args[0]);
int portNumber = Integer.valueOf(args[0]);
// System.out.println("waiting for connections on port " + portNumber + " ...\n ");
once = 3;
}
once = 3;
try
{
int portNumber1 = Integer.valueOf(args[0]);
serverSocket = new ServerSocket(portNumber1);
}
catch (IOException e)
{
System.out.println(e);
}
while (true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++)
{
if (threads[i] == null)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name, namesList, listName)).start();
break;
}
}
if (i == maxClientsCount)
{
//PrintStream os = new PrintStream(clientSocket.getOutputStream());
// os.println("Server too busy. Try later.");
// os.close();
// clientSocket.close();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
EDIT: it might also be possible to change threads[i] to threads[i+1] in order to keep track of different clients in certain parts of the code
What you need instead of this:
while (!closed)
{
os.println(inputLine.readLine() );
}
is this:
String line;
while ((line = inputLine.readLine()) != null)
{
os.println(line);
}
This will fall-through when ctrl/d or ctrl/z is pressed, as appropriate, and main() will then exit. Provided you have also made your threads daemons, the JVM will then exit.
NB this:
// After Control D/Z is pressed, this code will execute
isn't true, and this:
else if(line.equals(null) || line.equals("null") || line.contains("null"))
is drivel. line.equals(null) can never be true, by definition, otherwise a NullPointerException would have been thrown instead of calling .equals(): and why you should be interested in whether the user has typed "null", or something containing "null", is a mystery.
And why you are using synchronized(listName) in the main() method of an application which up to this point is single-threaded is another mystery.

Variable declaration from one class to another

the below codes are working fine(individually) i just want to pass letter[i] value from FindDrive class to Ziputils input file location such that i can zip pendrive data automatically.
FindDrive Class
package com.prosper;
import java.io.File;
public class FindDrive
{
/**
* Application Entry Point
*/
public static void main(String[] args)
{
String[] letters = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];
// init the file objects and the initial drive state
for ( int i = 0; i < letters.length; ++i )
{
drives[i] = new File(letters[i]+":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
// loop indefinitely
while(true)
{
// check each drive
for ( int i = 0; i < letters.length; ++i )
{
boolean pluggedIn = drives[i].canRead();
// if the state has changed output a message
if ( pluggedIn != isDrive[i] )
{
if ( pluggedIn ){
System.out.println("Drive "+letters[i]+" has been plugged in");
}
else
System.out.println("Drive "+letters[i]+" has been unplugged");
isDrive[i] = pluggedIn;
}
}
// wait before looping
try { Thread.sleep(100); }
catch (InterruptedException e) { /* do nothing */ }
}
}
}
The ZipUtils Class
package com.prosper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
private List <String> fileList;
private static final String OUTPUT_ZIP_FILE = "E:\\appu\\Folder.zip";
private static final String SOURCE_FOLDER = "E:\\appu\\"; //SourceFolder
public ZipUtils() {
fileList = new ArrayList < String > ();
}
public static void main(String[] args) {
ZipUtils appZip = new ZipUtils();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
public void zipIt(String zipFile) {
byte[] buffer = new byte[1024];
String source = new File(SOURCE_FOLDER).getName();
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
FileInputStream in = null;
for (String file: this.fileList) {
System.out.println("File Added : " + file);
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
try {
in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in .read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
} finally {
in.close();
}
}
zos.closeEntry();
System.out.println("Folder successfully compressed");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void generateFileList(File node) {
// add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename: subNote) {
generateFileList(new File(node, filename));
}
}
}
private String generateZipEntry(String file) {
return file.substring(SOURCE_FOLDER.length() + 1, file.length());
}
}
To pass data from one class to another, you can do the following:
1) Create an object of the class in your FindDrive class:
ZipUtils utils = new ZipUtils();
2) Pass the value to the method of that class:
utils.zipIt(letter[i])
I have inserted a few statements, which create a new object of ZipUtils class and call the method, however I do suggest you looking into Dependency Injection as well, if you want to improve your code quality here
package com.prosper;
import java.io.File;
public class FindDrive {
/**
* Application Entry Point
*/
public static void main(String[] args) {
String[] letters = new String[] {"A", "B", "C", "D", "E", "F", "G",
"H", "I"};
ZipUtils utils;
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];
// init the file objects and the initial drive state
for (int i = 0; i < letters.length; ++i) {
drives[i] = new File(letters[i] + ":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
// loop indefinitely
while (true) {
// check each drive
for (int i = 0; i < letters.length; ++i) {
boolean pluggedIn = drives[i].canRead();
utils = new ZipUtils();
utils.changeDirectory(letters[i]);
// if the state has changed output a message
if (pluggedIn != isDrive[i]) {
if (pluggedIn) {
System.out.println("Drive " + letters[i] + " has been plugged in");
} else {
System.out.println("Drive " + letters[i] + " has been unplugged");
}
isDrive[i] = pluggedIn;
}
}
// wait before looping
try {
Thread.sleep(100);
} catch (InterruptedException e) { /* do nothing */ }
}
}
}
To make changes to SOURCE_FOLDER after declaration, you need to make sure its not a constant i.e it is not final.
Add a method in ZipUtils:
private static String source_folder = "E:\\appu\\"; //SourceFolder
public void changeDirectory(String zip) {
source_folder = zip + ":\\";
}

Unexpected state occurred for AsyncDataSetIterator: runnable died or no data available

I'm trying to build a neural network using deep learning4j framework, I get the following error :
java.lang.IllegalStateException: Unexpected state occurred for AsyncDataSetIterator: runnable died or no data available" this exception
Here is my code
package com.neuralnetwork;
import com.sliit.preprocessing.NormalizeDataset;
import com.sliit.ruleengine.RuleEngine;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.datavec.api.records.reader.SequenceRecordReader;
import org.datavec.api.records.reader.impl.csv.CSVSequenceRecordReader;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
import weka.core.Instances;
import weka.core.converters.CSVLoader;
import weka.core.converters.CSVSaver;
import weka.filters.Filter;
import weka.filters.supervised.instance.StratifiedRemoveFolds;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Deep Belif Neural Network to detect frauds.
*/
public class FraudDetectorDeepBeilefNN {
private static final Log log = LogFactory.getLog(FraudDetectorDeepBeilefNN.class);
public int outputNum = 4;
private int iterations = 5;
private int seed = 1234;
private MultiLayerNetwork model = null;
public int HIDDEN_LAYER_COUNT = 8;
public int numHiddenNodes = 21;
public int inputs = 41;
private String uploadDirectory = "D:/Data";
private ArrayList < Map < String, Double >> roc;
public FraudDetectorDeepBeilefNN() {
}
public void buildModel() {
System.out.println("Build model....");
iterations = outputNum + 1;
NeuralNetConfiguration.Builder builder = new NeuralNetConfiguration.Builder();
builder.iterations(iterations);
builder.learningRate(0.001);
// builder.momentum(0.01);
builder.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT);
builder.seed(seed);
builder.biasInit(1);
builder.regularization(true).l2(1e-5);
builder.updater(Updater.RMSPROP);
builder.weightInit(WeightInit.XAVIER);
NeuralNetConfiguration.ListBuilder list = builder.list();
for (int i = 0; i < HIDDEN_LAYER_COUNT; i++) {
GravesLSTM.Builder hiddenLayerBuilder = new GravesLSTM.Builder();
hiddenLayerBuilder.nIn(i == 0 ? inputs : numHiddenNodes);
hiddenLayerBuilder.nOut(numHiddenNodes);
hiddenLayerBuilder.activation("tanh");
list.layer(i, hiddenLayerBuilder.build());
}
RnnOutputLayer.Builder outputLayer = new RnnOutputLayer.Builder(LossFunction.MCXENT);
outputLayer.activation("softmax");
outputLayer.nIn(numHiddenNodes);
outputLayer.nOut(outputNum);
list.layer(HIDDEN_LAYER_COUNT, outputLayer.build());
list.pretrain(false);
list.backprop(true);
MultiLayerConfiguration configuration = list.build();
model = new MultiLayerNetwork(configuration);
model.init();
//model.setListeners(new ScoreIterationListener(1));
}
public String trainModel(String modelName, String filePath, int outputs, int inputsTot) throws NeuralException {
try {
System.out.println("Neural Network Training start");
loadSaveNN(modelName, false);
if (model == null) {
buildModel();
}
System.out.println("modal" + model);
System.out.println("file path " + filePath);
File fileGeneral = new File(filePath);
CSVLoader loader = new CSVLoader();
loader.setSource(fileGeneral);
Instances instances = loader.getDataSet();
instances.setClassIndex(instances.numAttributes() - 1);
StratifiedRemoveFolds stratified = new StratifiedRemoveFolds();
String[] options = new String[6];
options[0] = "-N";
options[1] = Integer.toString(5);
options[2] = "-F";
options[3] = Integer.toString(1);
options[4] = "-S";
options[5] = Integer.toString(1);
stratified.setOptions(options);
stratified.setInputFormat(instances);
stratified.setInvertSelection(false);
Instances testInstances = Filter.useFilter(instances, stratified);
stratified.setInvertSelection(true);
Instances trainInstances = Filter.useFilter(instances, stratified);
String directory = fileGeneral.getParent();
CSVSaver saver = new CSVSaver();
File trainFile = new File(directory + "/" + "normtrainadded.csv");
File testFile = new File(directory + "/" + "normtestadded.csv");
if (trainFile.exists()) {
trainFile.delete();
}
trainFile.createNewFile();
if (testFile.exists()) {
testFile.delete();
}
testFile.createNewFile();
saver.setFile(trainFile);
saver.setInstances(trainInstances);
saver.writeBatch();
saver = new CSVSaver();
saver.setFile(testFile);
saver.setInstances(testInstances);
saver.writeBatch();
SequenceRecordReader recordReader = new CSVSequenceRecordReader(0, ",");
recordReader.initialize(new org.datavec.api.split.FileSplit(trainFile));
SequenceRecordReader testReader = new CSVSequenceRecordReader(0, ",");
testReader.initialize(new org.datavec.api.split.FileSplit(testFile));
DataSetIterator iterator = new org.deeplearning4j.datasets.datavec.SequenceRecordReaderDataSetIterator(recordReader, 2, outputs, inputsTot, false);
DataSetIterator testIterator = new org.deeplearning4j.datasets.datavec.SequenceRecordReaderDataSetIterator(testReader, 2, outputs, inputsTot, false);
roc = new ArrayList < Map < String, Double >> ();
String statMsg = "";
Evaluation evaluation;
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
model.fit(iterator);
evaluation = model.evaluate(testIterator);
} else {
model.fit(testIterator);
evaluation = model.evaluate(iterator);
}
Map < String, Double > map = new HashMap < String, Double > ();
Map < Integer, Integer > falsePositives = evaluation.falsePositives();
Map < Integer, Integer > trueNegatives = evaluation.trueNegatives();
Map < Integer, Integer > truePositives = evaluation.truePositives();
Map < Integer, Integer > falseNegatives = evaluation.falseNegatives();
double fpr = falsePositives.get(1) / (falsePositives.get(1) + trueNegatives.get(1));
double tpr = truePositives.get(1) / (truePositives.get(1) + falseNegatives.get(1));
map.put("FPR", fpr);
map.put("TPR", tpr);
roc.add(map);
statMsg = evaluation.stats();
iterator.reset();
testIterator.reset();
}
loadSaveNN(modelName, true);
System.out.println("ROC " + roc);
return statMsg;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error ocuured while building neural netowrk :" + e.getMessage());
throw new NeuralException(e.getLocalizedMessage(), e);
}
}
public boolean generateModel(String modelName) {
boolean status = false;
try {
loadSaveNN(modelName, true);
status = true;
} catch (Exception e) {
System.out.println("Error occurred:" + e.getLocalizedMessage());
}
return status;
}
private void loadSaveNN(String name, boolean save) {
File directory = new File(uploadDirectory);
File[] allNN = directory.listFiles();
boolean status = false;
try {
if (model == null && save) {
buildModel();
}
if (allNN != null && allNN.length > 0) {
for (File NN: allNN) {
String fnme = FilenameUtils.removeExtension(NN.getName());
if (name.equals(fnme)) {
status = true;
if (save) {
ModelSerializer.writeModel(model, NN, true);
System.out.println("Model Saved With Weights Successfully");
} else {
model = ModelSerializer.restoreMultiLayerNetwork(NN);
}
break;
}
}
}
if (!status && save) {
//File tempFIle = File.createTempFile(name,".zip",directory);
File tempFile = new File(directory.getAbsolutePath() + "/" + name + ".zip");
if (!tempFile.exists()) {
tempFile.createNewFile();
}
ModelSerializer.writeModel(model, tempFile, true);
}
} catch (IOException e) {
System.out.println("Error occurred:" + e.getMessage());
}
}
public String testModel(String modelName, String[] rawData, Map < Integer, String > map, int inputs, int outputs, String ruleModelSavePath) throws Exception {
String status = "";
String fpath = uploadDirectory;
FileWriter fwriter = new FileWriter(uploadDirectory + "original/insertdata.csv", true);
fwriter.write("\n");
fwriter.write(rawData[0]);
fwriter.close();
if (model == null) {
loadSaveNN(modelName, false);
}
NormalizeDataset norm = new NormalizeDataset(uploadDirectory + "original/insertdata.csv");
norm.updateStringValues(map);
norm.whiteningData();
norm.normalizeDataset();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(uploadDirectory + "originalnorminsertdata.csv")));
String output = "";
String prevOutput = "";
while ((output = bufferedReader.readLine()) != null) {
prevOutput = output;
}
bufferedReader.close();
File readFile = new File(uploadDirectory + "normtest.csv");
if (readFile.exists()) {
readFile.delete();
}
readFile.createNewFile();
PrintWriter writer = new PrintWriter(readFile);
writer.println(prevOutput);
writer.flush();
writer.close();
SequenceRecordReader recordReader = new CSVSequenceRecordReader(0, ",");
recordReader.initialize(new org.datavec.api.split.FileSplit(new File(uploadDirectory + "normtest.csv")));
DataSetIterator iterator = new org.deeplearning4j.datasets.datavec.SequenceRecordReaderDataSetIterator(recordReader, 2, outputs, inputs, false);
INDArray outputArr = null;
while (iterator.hasNext()) {
DataSet ds = iterator.next();
INDArray provided = ds.getFeatureMatrix();
outputArr = model.rnnTimeStep(provided);
}
//INDArray finalOutput = Nd4j.argMax(outputArr,1);
double result = Double.parseDouble(Nd4j.argMax(outputArr, 1).toString());
if (result == 0.0) {
status = "Normal Transaction";
} else {
status = "Fraud Transaction, ";
bufferedReader = new BufferedReader(new FileReader(new File(uploadDirectory + "original/insertdata.csv")));
String heading = "";
heading = bufferedReader.readLine();
bufferedReader.close();
File ruleFile = new File(uploadDirectory + "normrules.csv");
if (ruleFile.exists()) {
ruleFile.delete();
}
ruleFile.createNewFile();
PrintWriter writeNew = new PrintWriter(ruleFile);
writeNew.println(heading);
writeNew.println(rawData[0]);
writeNew.flush();
writeNew.close();
RuleEngine engine = new RuleEngine(fpath + "original/insertdata.csv");
engine.geneateModel(ruleModelSavePath, false);
String finalStatus = status + "Attack Type:" + engine.predictionResult(uploadDirectory + "normrules.csv");
status = finalStatus;
}
return status;
}
public void setUploadDirectory(String uploadDirectory) {
this.uploadDirectory = uploadDirectory;
}
public static void main(String[] args) {
FraudDetectorDeepBeilefNN neural_network = new FraudDetectorDeepBeilefNN();
System.out.println("start=======================");
try {
neural_network.inputs = 4;
neural_network.numHiddenNodes = 3;
neural_network.HIDDEN_LAYER_COUNT = 2;
neural_network.outputNum = 2;
neural_network.buildModel();
String output = neural_network.trainModel("nn", "D:/Data/a.csv", 2, 4);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList < Map < String, Double >> getRoc() {
return roc;
}
}
Here is the 1st few lines of my dataset :
length,caplen,hlen,version,output
60,60,6,0,normal
243,243,8,0,normal
60,60,6,0,neptune
60,60,6,0,neptune

Why do I get lagspikes from sound?

I'm developing a game in Java, and have made an attempt at coding a simple sound system for it made of two class files: one that handles them, and one for each sound file loaded.
My problem is that every once in a while I get a huge lagspike which means a complete stop for like a second or two, really interrupting gameplay. I'm suspecting Garbage control but I'm not entirely sure. The only thing I know for a fact is that the source of the problem lies in the sounds.
Here's my SoundHandler.java:
(The loading of sounds is unimportant, as far as I know it should be unrelated to the problem)
package Classes;
import java.io.*;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.FloatControl;
public class SoundHandler {
Sound Sounds[] = new Sound[1];
public SoundHandler()
{
if(!LoadSounds("Sounds.cfg"))
System.out.print("Failiure upon loading sounds!");
}
public boolean LoadSounds(String FileName)
{
String line = "";
String SoundName = "";
String SoundFile = "";
String[] token3 = new String[10];
boolean EndOfFile = false;
int LineCount = 0;
BufferedReader characterfile = null;
try
{
characterfile = new BufferedReader(new FileReader(GameMain.GameFolder+"Data/"+FileName));
}
catch(FileNotFoundException fileex)
{
System.out.println(FileName+": file not found.");
return false;
}
while(!EndOfFile && line != null)
{
try
{
line = characterfile.readLine();
if(line != null)
{
if(line.indexOf("//") == -1 && !line.equals(""))
LineCount++;
}
}
catch(IOException ioexception)
{
if(LineCount == 0)
{
System.out.println(FileName+": error loading file.");
return false;
}
EndOfFile = true;
}
}
try { characterfile.close(); } catch(IOException ioexception) { characterfile = null; }
Sounds = new Sound[LineCount];
EndOfFile = false;
LineCount = 0;
try
{
characterfile = new BufferedReader(new FileReader(GameMain.GameFolder+"Data/"+FileName));
}
catch(FileNotFoundException fileex)
{
System.out.println(FileName+": file not found.");
return false;
}
try
{
line = characterfile.readLine();
if(line != null)
if(line.indexOf("//") == -1 && !line.equals(""))
LineCount++;
}
catch(IOException ioexception) { }
while(EndOfFile == false && line != null) {
if(line.indexOf("//") == -1 && !line.equals(""))
{
line = line.trim();
line = line.replaceAll("\t\t", "\t");
line = line.replaceAll("\t\t", "\t");
line = line.replaceAll("\t\t", "\t");
line = line.replaceAll("\t\t", "\t");
int Spot = line.indexOf("\t");
SoundName = line.substring(0,Spot);
SoundFile = line.substring(Spot+1);
Sounds[LineCount-1] = new Sound(SoundName,SoundFile);
}
try {
line = characterfile.readLine();
if(line != null)
if(line.indexOf("//") == -1 && !line.equals(""))
LineCount++;
} catch(IOException ioexception1) { EndOfFile = true; }
}
try { characterfile.close(); } catch(IOException ioexception) { }
return true;
}
public File GetSoundFile(String Name)
{
File result = null;
for(int i = 0; i < Sounds.length; i++)
if(Sounds[i].Name.equals(Name))
result = Sounds[i].File;
return result;
}
public Sound GetSound(String Name)
{
Sound result = null;
for(int i = 0; i < Sounds.length; i++)
if(Sounds[i].Name.equals(Name))
result = Sounds[i];
return result;
}
public int GetSoundID(String Name)
{
int result = 0;
for(int i = 0; i < Sounds.length; i++)
if(Sounds[i].Name.equals(Name))
result = i;
return result;
}
Double MasterVolume = 0.75;
public float CalcVolume(double Vol)
{
float result = 0f;
result = -40.0f + (float)(MasterVolume*Vol*40);
if(result < -40.0f)
result = -40.0f;
if(result > 0.0f)
result = 0.0f;
return result;
}
public boolean PlaySound(String SoundName, double Vol)
{
int ID = GetSoundID(SoundName);
try
{
Clip CurrentClip;
Sounds[ID].Reset(false);
CurrentClip = (Clip) AudioSystem.getLine(Sounds[ID].info);
CurrentClip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
CurrentClip.open(Sounds[ID].sound);
FloatControl Volume;
Volume = (FloatControl) CurrentClip.getControl(FloatControl.Type.MASTER_GAIN);
Volume.setValue(CalcVolume(Vol));
CurrentClip.start();
}
catch(LineUnavailableException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
return true;
}
}
Here's my Sound.java:
package Classes;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
public class Sound {
public String Name = "";
public File File = null;
AudioInputStream sound;
DataLine.Info info;
Clip clip;
public Sound(String iName, String FileName)
{
Name = iName;
File = new File(GameMain.GameFolder+"Sound/"+FileName+".wav");
Reset(true);
}
public void Reset(boolean init)
{
try
{
if(!init)
sound.close();
sound = AudioSystem.getAudioInputStream(File);
info = new DataLine.Info(Clip.class, sound.getFormat());
}
catch(IOException e) { e.printStackTrace(); }
catch(UnsupportedAudioFileException e) { e.printStackTrace(); }
}
}
I've tried searching around for a general way to implement sounds in a game, most I've encountered didn't feature multiple instances of the same sound file running at once, this is what I have so far. I'm sure there are a few tiny inefficiencies especially in the loading code, but there's got to be some leak I'm missing. Any tips for custom GC usage are also welcome.
Thanks in advance.
It might be easier to research concurrent threading on the Java Oracle site... I can get a link. There are ways to sync threads together and they do have examples.
Oracle Concurrency Documenation! ->> Object Syncing

Categories