i am using the following in one of my application.
public static void concatenation(List<String> commands) throws IOException {
if (commands.get(1).equals(">")) {
String path = history.getFilePath();
File file = new File(path + "\\" + commands.get(2));
if (file.exists() && file.isFile()) {
try (FileWriter writer = new FileWriter(file)) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Write to file. Press Ctrl+C to stop.");
while (true) {
try {
line = scanner.nextLine();
writer.write(line + System.lineSeparator());
writer.flush();
} catch (Exception e) {
System.out.println("Interrupted. Stopping...");
break;
}
}
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
} else {
System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
}
}
i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?
Related
I created the mobile app on client side for Android successfully.
Then Server side, that is windows server code also created. I can able to type all the letters numbers and all.
My problem is using shift key and "#" key. I need "#" into my project. When I press the "#" crashes the connection and says...
Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at pcHotkey.keyboardServer$Capitalizer.run
Now, how should I type "#" with my app. Then I press shift key it was passing correctly and it was not stopping the pressed state.
My code goes here,
1st class:
aMap.put("Shift", KeyEvent.VK_SHIFT);
aMap.put("At", KeyEvent.VK_AT);
try{
robo = new Robot();
}
catch(Exception e)
{}
ServerSocket listener = new ServerSocket(9898);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
2nd class :
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
out.println("Enter a line with only a period to quit\n");
while (true) {
String input = in.readLine();
System.out.println(input);
if(input.equals("Caps")){
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
;
}
else if(input.equals("At"))
{
log("Log Value : "+ input);
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
robo.keyPress(aMap.get("At"));
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
}
else
robo.keyPress(aMap.get(input));
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
I did by passing the keycode of "SHIFT" and "2". Problem got fixed now.
I made a code for my system which would update a record in my text file database but I cant seem to make it work. The code doesnt have any error. its just not doing what I intend it to do
public static void Update() throws Exception {
File tempfile2 = new File("temp.txt");
tempfile2.createNewFile();
FileInputStream tempFStream = new FileInputStream(tempfile2);
BufferedReader read = new BufferedReader(new InputStreamReader(tempFStream));
System.out.print("Product Number: ");
String searchnum = br.readLine();
try {
LoadFile();
boolean found = false;
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (!searchnum.equals(record[0])) {
found = true;
FileWriter fw = new FileWriter(tempfile2, true);
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
fw.close();
}
}
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (searchnum.equals(record[0])) {
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
System.out.print("\t\t\tAre you sure you want to replace the records?<Y/N>: ");
String del = br.readLine();
if (del.equals("Y") || del.equals("y")) {
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\n\t\t\t------Update Record Form------");
System.out.print("\n\n\t\t\tProduct Number : ");
int prodnum = Integer.parseInt(br.readLine());
System.out.print("\t\t\tCategory : ");
String cat = br.readLine();
System.out.print("\t\t\tProduct Name :");
String prodname = br.readLine();
System.out.print("\t\t\tPrice: ");
String price = br.readLine();
System.out.print("\t\t\tQuantity : ");
String quan = br.readLine();
read.close();
database.delete();
boolean rename = false;
if (rename = tempfile2.renameTo(database)) {
InsertRecords(prodnum, cat, prodname, price, quan);
System.out.println("\t\t\tSuccessfully Edited!");
exiting();
} else {
System.out.print("Edit Failed!");
}
} else if (del.equals("N") || del.equals("n")) {
MainMenu();
}
}
if (!searchnum.equals(record[1])) {
System.out.println("\n\t\t\tNo Record Found.");
Thread.sleep(2000);
exiting();
}
}
} catch (Exception e) {
System.out.print("File Empty!");
}
}
public static void LoadFile()throws Exception
{
list.clear();
FileInputStream fis = new FileInputStream(database);
BufferedReader read = new BufferedReader(new InputStreamReader(fis));
row = 0;
while(read.ready())
{
list.add(read.readLine());
row++;
}
read.close();
}
Everytime I run this... it would work until Product Number: User input and after entering a number it would directly display File is empty which is at the end of the program. its as if the try/catch is ignored. I definitely did something wrong but I dont know what I did wrong. Anyone shed me some light? Thanks
and with the e.printStackTrace(); here's what displayed after entering a product number...
java.lang.ArrayIndexOutofBoundException:5
at SnackTimeInventorySystem.Update<SnackTimeInventorySystem.java:525>
at SnackTimeInventorySystem.MainMenu<SnackTimeInventorySystem.java:66>
at SnackTimeInventorySystem.Login<SnackTimeInventorySystem.java:369>
at SnackTimeInventorySystem.main<SnackTimeInventorySystem.java:14>
Turns out I only had 5 entries on my array but declared 6 entries to be written
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
So I just had to delete record[5] and fixed the problem thanks to Tom
I need to read a line from a file, and output it onto the console.
I have tried using the BufferedReader however this is messing up my StreamTokenizer.lineno(), so I was wondering whether I could tackle this from a different angle.
This is the snippet of my code which is outputting to another file
try {
PrintWriter out = new PrintWriter(new FileWriter("Parsed_Files" + timeStamp + ".csv"));
boolean eof = false;
int count = 0;
do {
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_EOF:
System.out.println("End of File encountered.");
eof = true;
break;
default:
if (token == '\'' || token == '\"') {
if (st.sval.length() == 3) {
if (isNumeric(st.sval)) {
//output to the CSV File
System.out.println("Writing to File");
out.println("File Name: " + fileName);
out.println("Code Number: " + st.sval);
out.println("Line: " + br.readLine());
out.println("Line Number: " + st.lineno());
out.println("-----------------------------------"
+ "------------------------------------");
out.println("");
count++;
}
}
}
}
} while (!eof);
}
I've written this code to read in a file and then ask for a mark, for each name in the file. And if the mark is over 40 its a pass and below is a fail and writes each name to the corresponding file. But I get an error at line 27 which: while(namesFile.hasNext() here's my code:
import java.io.*;
import java.util.*;
public class TestResults {
public static void main(String[] args) {
String errs = "";
Scanner k = new Scanner(System.in);
try {
try (
Scanner namesFile = new Scanner(new File("Names.txt"));
PrintWriter passFile = new PrintWriter("Pass.txt");
PrintWriter failFile = new PrintWriter("Fail.txt");) {
while (namesFile.hasNext()) {
try {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
}
} // Checks to see if file is there.
catch (IOException ioe) {
System.out.println("ERROR: " + ioe.getMessage());
}
}
}
public class TestResults {
public static void main(String[] args) {
Scanner namesFile;
PrintWriter passFile;
PrintWriter failFile;
String errs = "";
Scanner k = new Scanner(System.in);
try {
try {
namesFile = new Scanner(new File("D:/Names.txt"));
passFile = new PrintWriter("D:/Pass.txt");
failFile = new PrintWriter("D:/Fail.txt");
try {
while (namesFile.hasNext()) {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
catch(IOException ioe){
System.out.println("ERROR: " + ioe.getMessage());
}
} // Checks to see if file is there.
catch (Exception e) {
}
}
}
I wanted to set a timeout when a client read. the routine supposed to throw an InterruptedIOException but instead it throws NoSuchElementException on System.out.println("echo: " + _in.nextLine()); what am I doing wrong ?
this is my methode
public void startUserInput()
{
try {
_out = new PrintWriter(_echoSocket.getOutputStream(), true);
_in = new Scanner(new InputStreamReader(_echoSocket.getInputStream()));
Scanner stdIn = new Scanner(new InputStreamReader(System.in));
System.out.print("Input: ");
while (stdIn.hasNextLine()) {
_out.println(stdIn.nextLine());
System.out.println("echo: " + _in.nextLine());
System.out.print("Input: ");
}
stdIn.close();
}catch (InterruptedIOException exception){
System.err.println("The server is not responding " + _serverHostname);
}
catch (IOException e) {
System.out.println("error" + e.getLocalizedMessage());
}}
and this is my connection
public boolean establishConnection()
{
System.out.println ("Connecting to the host " +
this.getServerHostname() + " au port " + this.getServerPort());
try {
_echoSocket = new Socket();
_echoSocket = new Socket(this.getServerHostname(), this.getServerPort());
_echoSocket.setSoTimeout(10000);
System.out.println(_echoSocket.getOutputStream());
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + this.getServerHostname());
return false;
} catch (IOException e) {
System.err.println("Error while connecting to the server : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
Thanks
The reason is that when you invoked _in.nextLine() there is no line to be read in from the from the Scanner object _in.
What you did in the while loop was to check for stdIn.hasNextLine() but you did not check if _in has a nextLine() that can be read.
For details on the exception, you can check out:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()
hope it helps :) Cheers!