Barcode print in java while barcode scanner scans - java

I want to read the barcode and print it in a console in a simple java program as soon as the barcode scans on top of any barcode. Is there any way?

final Scanner scanner;
try
{
scanner = new Scanner();
try {
scanner.release();
scanner.close();
} catch (Exception e) {
}
scanner.open("MotorolaScannerUSB");
scanner.claim(100);
scanner.setDeviceEnabled(true);
scanner.setDataEventEnabled(true);
scanner.addDataListener(new DataListener()
{
public void dataOccurred(DataEvent arg0) {
Scanner scn = (Scanner) arg0.getSource();
if (scn.equals(scanner)) {
try {
scanner.claim(100);
System.out.println(new String(scanner.getScanData()));
scanner.claim(100);
scanner.setDeviceEnabled(true);
scanner.setDataEventEnabled(true);
} catch (JposException e) {
e.printStackTrace();
}
}
}
});
}
catch (Exception e) {
System.err.println("error");
}

Related

Scanner in a function. Closing the Scanner is causing trouble

I am getting flickering screen when closing the scanner,but without closing it works fine.
public void removeBranch() {
try {
Scanner input=new Scanner(System.in);
System.out.print("Enter branch id to remove:");
int Id=input.nextInt();
int toDelete=branchPresent(Id);
if(toDelete!=-1) {
branches.remove(toDelete);
System.out.println("Branch removed");
}else {
System.out.println("\n No such Branch!\n");
}
} catch (Exception e) {
System.out.println("\nsomething went wrong while removing !\n");
}
}
Close the scanner in finally block
try{
Scanner input=new Scanner(System.in);
// Do stuff
}
catch {
// Handle exception
}
finally {
input.close();
}

NoSuchElementException Scanner not waiting

I am working on my first server project for school and I am receiving a NoSuchElementException when reaching the code below in my client. From my understanding, the way I have written it, the scanner should be waiting for the server to send back a string. Instead it seems to be jumping right to the exception. In the server code (second below) I have the output that is supposed to return all strings in an array. My goal is to have the client print all of the strings in the text area (status).
static void runClient() {
Socket client = null;
PrintWriter output = null;
Scanner input = null;
try {
client = new Socket("localhost", 5007);
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream());
output.println(game);
output.println(numberOfPicks);
output.flush();
pStr("Data Sent");
while (true) {
pStr("Waiting for Server");
status.appendText(input.nextLine());
if (!input.hasNext())
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
client.close();
} catch (Exception e) {
}
}
}
private static void pStr(String string) {
System.out.println(string);
}
}
PARTIAL SERVER CODE BELOW
public void run() {
PrintWriter output = null;
Scanner input = null;
try {
// Get input and output streams.]
input = new Scanner(connection.getInputStream());
output = new PrintWriter(connection.getOutputStream());
String game;
int quickPicks;
try {
game = input.nextLine();
quickPicks = Integer.parseInt(input.nextLine());
switch (game) {
case "PowerBall":
ansStr = new pickNumbers(game, quickPicks, 69, 26).getQuickPicks();
break;
case "MegaMillions":
ansStr = new pickNumbers(game, quickPicks, 70, 25).getQuickPicks();
break;
case "Lucky4Life":
ansStr = new pickNumbers(game, quickPicks, 48, 18).getQuickPicks();
break;
default:
throw new RuntimeException("Incorrect Game");
}
} catch (Exception e) {
output.println(e.getMessage());
}
for (int i = 0; i < ansStr.length; i++) {
output.println(ansStr[i]);
//output.flush();
}
} catch (Exception e) {
pStr(e.getMessage());
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
connection.close();
} catch (Exception e) {
}
}
}
}
How about nesting status.appendText(input.nextLine()); in a test for hasNextLine e.g:
if(input.hasNextLine()){
status.appendText(input.nextLine());
}

Java input/output stream for primitive values

I've been reading about java streams and decided to make a simple input class that will read input from the user(keyboard) and return it back.The problem is that i don't know which stream-class to use for simple,primitive values.I made UserInput class using the DataInputStream ,but noticed that i didn't work,because,as i understood,the DataInputStream supports only bufferedStream,and the problem is that i don't know how to flush the input after i read something(There is no flush method).How do i fix this,or could you suggest me another input stream for primitive values(without casting and using of Integer.valueOf() e.t.c methods).Also,i made UserInput with BufferedReader,but i didn't like it,because i had to use methods like:Double/Integer/Short/etc.valueOf()
Here is the code of my class :
import java.io.*;
import java.util.InputMismatchException;
public class UserInput {
static DataInputStream reader;
public UserInput() {
reader = new DataInputStream(System.in);
}
public int getInt() {
int result = -1;
try {
result = reader.read();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public double getDouble() {
double result = -1;
try {
result = reader.readDouble();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public float getFloat() {
float result = -1f;
try {
result = reader.readFloat();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public long getLong() {
long result = -1l;
try {
result = reader.readLong();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public short getShort() {
short result = -1;
try {
result = reader.readShort();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public String getString() {
String result = " ";
try {
result = reader.readUTF();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return empty character ");
}
return result;
}
public char getChar() {
char result = ' ';
try {
result = (char) reader.read();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return empty character ");
}
return result;
}
/**
* Closes the buffer.
*
*/
public void close() {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Inputstream has been closed.");
}
}
}
I think there's a misunderstanding here - you're treating System.in (which is a stream of characters) as a DataInputStream (which is a stream of bytes - something very different)
If your intention is to read various types from System.in you could just use operations similar to this:
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
System.out.println("Got string: " + s);
double d = scanner.nextDouble();
System.out.println("Got double: " + d);
So your class could be set up like this:
public UserInput() {
scanner= new Scanner(System.in);
}
Otherwise if your intention was to read and write primitives, you'd need to first write those primitives onto a DataOutputStream, which is equivalent to a DataInputStream. The System.in would not be relevant to the exercise in this case.

How to monitor a text file in java

I am making an application that will display a gui and read a text file. When the contents of the text file changes it will execute changes to the gui. However i need the gui to constantly be reading and checking the textfile for changes. I have tried thread.sleep() which just takes control and no code works other than the loop. After looking around i found reference to swing timers and running in new threads that weren't the EDT. This stuff is lost on me and I can find no way to implement it. Any help would be appreciated.
public void run() {
initComponents();
while(true){System.out.println("ok");
try {
try {
File myFile = new File("C:\\Users\\kyleg\\OneDrive\\Documents\\123.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
System.out.println(in);
switch(in){
case("1"):
break;
case("2"):
break;
case("3"):
break;
}
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is just a simple code for file monitoring, hope it can help you.
File f = new File("Path_to_the_file");
new Thread(new Runnable() {
#Override
public void run() {
long l = f.lastModified();
String s = "";
while (true) {
if (f.lastModified() == l) {
System.out.print();
} else {
try {
Scanner sc = new Scanner(f);
s = "";
while (sc.hasNext()) {
s += sc.nextLine();
s += "\n";
jTextArea1.setText(s);
}
System.out.println(false);
l = f.lastModified();
sc.close();
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}
}
}
}).start();

Java read file with scanner

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

Categories

Resources