BufferedReader problem
I have to read twice the same file
the first time i have to read only the last line
the second time i have to read every single line
when i try to do it i get an IO error stream closed
BufferedReader in = null;
BufferedReader in1 = null;
InputStreamReader isr = null;
InputStreamReader isr1 = null;
try{
isr = new InputStreamReader(txt, "UTF-8");
catch (UnsupportedEncodingException i)
System.err.println("Exception encoding");
try{
in = new BufferedReader(isr);
in1 = new BufferedReader(isr1);
String strLine = null, tmp;
while ((tmp = in1.readLine()) != null)
strLine = tmp;
String lastLine = strLine;
System.out.println(lastLine);
in1.close();
List records = new ArrayList();
String lineItem;
Riga1 u = new Riga1();
while ((lineItem = in.readLine()) != null) { ...
How can I solve it ?
Thanks
Gianni
Now i get stream not marked !
sigh ! why ?
public class TxtToXml implements Const{
public static void converti(InputStream txt, String xml)
BufferedReader in = null;
InputStreamReader isr = null;
try{
isr = new InputStreamReader(txt, "UTF-8");
catch (UnsupportedEncodingException i)
System.err.println("Eccezione di encoding");
try{
in = new BufferedReader(isr);
String strLine = null, tmp;
in.mark(1);
while ((tmp = in.readLine()) != null)
strLine = tmp;
String lastLine = strLine;
System.out.println(lastLine);
catch (IOException e) {
System.err.println("Error: " + e);
try{
in= new BufferedReader(isr);
List records = new ArrayList();
String lineItem;
Riga1 u = new Riga1();
in.reset();
while ((lineItem = in.readLine()) != null) {
String tiporecord = lineItem.substring(0, 2);
int tiporecordInt = Integer.parseInt(tiporecord);
System.out.println("tiporecordInt " + tiporecordInt);
switch (tiporecordInt) {
// PARAMETRI
case 1 : //Riga1 dati del patronato
u.parse(lineItem,tiporecordInt);
break;
case 2 : //Riga2 richiesta
u.parse(lineItem,tiporecordInt);
case 3 : //Riga3 prodotto della richiesta max 5 prodotti
u.parse(lineItem,tiporecordInt);
// u.scrivixml(1);
// System.out.println("caso 3 ");
break;
case 4 : //Riga4 Soggetto della richiesta max 15 soggetti
u.parse(lineItem,tiporecordInt);
u.scrivixml(1);
// System.out.println("caso 3 ");
break;
in.close();
catch (IOException e) {
System.err.println("Error: " + e);
}
Similar Messages
-
BufferedReader Problem (inserting space after every character)
(This is a message I sent to an Aglet forum, however I thought maybe someone here could help me with the BufferedReader problem...with the spacing...read below)
-Blake
ok here's what I'm attempting to do.
I have a Master Aglet that creates a slave which is dispatched to a remote site. The Slave then opens a log file, reads it, and then is supposed to read the file line by line and send each line as a message back to the Master. As the master receives each line it appends the line to the window it created earlier.
I don't know what the problem is...it won't display the log file in the master window.
It does display each line on the console window.I added a println() function to make sure the String array was getting the information. There is a small problem with that as well because it inserts a space after EVERY character (BufferedReader problem??)...what is up with that? for example:
If the log file looked like: This is a log file entry.
the console looks like this when it is printed: T h i s i s a l o g f i l e e n t r y .
.... I had done something in a similiar program...and it worked just fine. here's some source code:
<b>Master:</b>
else if (msg.sameKind("Log")) {
try {
//println for testing purposes
System.out.println(msg.getArg());
appendMessage(" " + msg.getArg() + "test \n");
} catch (Exception e) {
System.out.println(e.toString());
<b>Slave: </b>
File log = new File("C:\\Aglets2.0.2\\public\\WINDOWSUPDATE.log");
FileReader fr = null;
try{
fr = new FileReader(log);
} catch (FileNotFoundException e) {
System.out.println(e);
BufferedReader br = new BufferedReader(fr);
//Get filename of log
try {
Message msg = new Message("FileName", log.getName());
mProxy.sendOnewayMessage(msg);
} catch (InvalidAgletException iae) {
System.out.println(iae.toString());
} catch (Exception e) {
System.out.println(e.toString());
//read each line of file and send back to Master as a message
try{
int i = 0;
while ((s = br.readLine()) != null) {
i++;
count = i;
for (int j = 0; j < count; j++)
System.out.println(s[j]);
//send message back to Master Aglet with log file information
try {
Message msg = new Message("Log", s[j]);
mProxy.sendMessage(msg);
} catch (InvalidAgletException iae) {
System.out.println(iae.toString());
} catch (Exception e) {
System.out.println(e.toString());
//close file reader
fr.close();
} catch (IOException e) {
System.out.println(e.toString());
}actually i did declare s, you just don't see it there because i only posted some of the code....
I fixed the "spacey" problem by using a FileInputStream instead of a bufferedreader....
like this (i'll post the whole code here:
public class Slave extends BlindAglet {
AgletProxy mProxy = null;
boolean back = false;
char[] c = new char[1000];
BufferedReader br = null;
int count;
// Do some tasks when the aglet is created
public void onCreation(Object init) {
// Must make a note of the master here
mProxy = (AgletProxy)init;
// Add our own listener and adapter
addMobilityListener(
new MobilityAdapter() {
// Using this as a safety check in case we get caught in a loop in the same host
public void onArrival(MobilityEvent event) {
try {
mProxy.sendMessage(new Message("NewSlaveProxy", getAgletContext().getAgletProxy(getAgletID())));
} catch (InvalidAgletException iae) {
System.out.println(iae);
} catch (NotHandledException ex) {
System.out.println(ex);
} catch (MessageException ex) {
System.out.println(ex);
//Are we back to origin?
if(back) {
back = false;
try{
FileWriter fw = new FileWriter("test.txt");
for (int i = 0; i < count; i += 2){
fw.write(c);
fw.close();
} catch (IOException e) {
System.out.println(e);
dispose();
dispose();
); /* End of Adapter */
public void run() {
// Are we at home base?
if (atHome()) {
try {
dispatch(new URL("atp://darklord:4434"));
} catch (Exception e) {
System.out.println(e.toString());
try{
File log = new File("C:\\Aglets2.0.2\\public\\WINDOWSUPDATE.log");
FileInputStream f0 = new FileInputStream(log);
//Get filename of log
try {
System.out.println(log.getName());
Message msg = new Message("FileName", log.getName());
mProxy.sendOnewayMessage(msg);
} catch (InvalidAgletException iae) {
System.out.println(iae.toString());
} catch (Exception e) {
System.out.println(e.toString());
//read each line of file and send back to Master as a message
try{
int size = f0.available();
int i = 0;
for (i = 0; i < size; i++) {
c[i] = (char) f0.read();
//send message back to Master Aglet with log file information
try {
Message msg = new Message("Log", c[i]);
mProxy.sendOnewayMessage(msg);
} catch (InvalidAgletException iae) {
System.out.println(iae.toString());
} catch (Exception e) {
System.out.println(e.toString());
count = i;
} catch (IOException e) {
System.out.println(e.toString());
} catch (FileNotFoundException e) {
System.out.println(e);
back = true;
returnHome();
* Returns true if the current host is our origin
public boolean atHome() {
if (getAgletInfo().getOrigin().equals(getAgletContext().getHostingURL().toString()))
return true;
else
return false;
* Allows a slave to contact it's master and ask for a retraction.
public void returnHome() {
try {
Message msg = new Message("RetractMe");
msg.setArg("url", getAgletContext().getHostingURL());
msg.setArg("id", getAgletID());
mProxy.sendOnewayMessage(msg);
} catch (InvalidAgletException iae) {
System.out.println(iae.toString());
} catch (Exception e) {
System.out.println(e.toString());
* Return a reference to our Master's proxy
public AgletProxy getMasterProxy() {
return mProxy;
} /* End of Class -
Hello all.
I'm trying to use a BufferedReader to read in data from a file that is in a Jar. Locally of course it works but or WebStart I get java.Security.AccessControlException which leads me to believe that it is trying to read a local file and since my program is not signed, it fails. The jars will not be signed since there is no need for it given that all files will be contained withing the same jar (called: files.jar). I know that I can access this jar because I am getting all sorts of Images from it over Java WebStart. Here is my code:
public Vector<String []> readFiletoVectorOfArrays (String delimeter, String path){
///unrelated code
System.out.println ("readFileToVectorOfArrays().path: " + path);
InputStream instream = getClass().getResourceAsStream(path);
System.out.println ("instream.toString() = " +instream.toString());
InputStreamReader infile = new InputStreamReader(instream);
System.out.println ("infile.toString = " +infile.toString());
BufferedReader inbuf = new BufferedReader(infile);
// unrelated code
}Any help is greatly appreciated.>
nevermind, found the bug. >Glad you sorted it. Thanks for having the sense to report the solution back to the forum.
>
..it was somewhere else completely involving JFileChoosers which of course do not work over JNLP. ...>Sure they do, as your comment above about the jars not being signed indicates you already understand. JFileChoosers work just fine for a signed app. that requests extended permissions.
OTOH, local files can be accessed for either reading or writing even in sandboxed web start applications by using the JNLP API's FileOpenService* or FileSaveService. I had some examples up at my site, but it is offline for the moment.
* <http://java.sun.com/j2se/1.5.0/docs/guide/javaws/jnlp/javax/jnlp/FileOpenService.html>
An aside. I had a look at this post as soon as it first showed up. It looked to me there could be no way that code could fail in the way described, but without a complete example I did not feel confident enough to make comment.
If you can provide an example off your server, or even a post a 'complete' example of code and JNLP file that fails for other people as it does for you - that can often speed the resolution process. I am such a fan of the complete example that I wrote an article on it, which is fortunately mirrored a number of places besides my site. Here is one mirror.. <http://homepage1.nifty.com/algafield/sscce.html>
In this case, the process of preparing an SSCCE would hopefully have revealed the actual source of the error (by a simple process of eliminating unnecessary code). -
No BufferedReader Problem!
I am developing a MIDP application, there is no BufferedReader class to read the file Input. Any other method to cope with it? thanks
If you are dealing with just ASCII characters, a BufferedInputStream will work.import java.io.*;
class BuffReader {
public static void main(String[] args) throws IOException {
File f = new File("afile.txt");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
byte[] b = new byte[(int)f.length()];
in.read(b,0,b.length);
in.close();
//construct a String from the byte array:
String s = new String(b);
System.out.println(s);
}Otherwise, you can have a look at source in java.io.* (Reader.java, InputStreamReader.java, BufferedReader.java).
Cheers! -
I'm coding a program that takes a input like this :
Sample Input
1 11 5
2 6 7
3 13 9
12 7 16
14 3 25
19 18 22
23 13 29
24 4 28
So I wrote a code like this :
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(input);
int leftX = Integer.parseInt(st.nextToken());
int height = Integer.parseInt(st .nextToken());
int rightX = Integer.parseInt(st.nextToken());
.... rest of the code....
But unlike I expected, the program did not pass the while loop.
When I observed in debugging mode, when "br.readLine()" has no more strings to read,
the whole program just becomes idle doing nothing, and it does not proceed further.
Is there any problem with my code there? I've been trying to figure it out for hours... Please help!!!myunghajang wrote:
Why doesn't it work in a way I intended? BufferedReader returns null if there is no more string to read, and what's the problem?
It's so frustrating...The computer doesn't have a mind reading input, how is your program supposed to know you have finished typing the input?
If you put the data in a file and redirect it into your program on the command line it will work (because the file knows where its end is)
Your program could instead assume that a blank line is you end of input. -
Problems reading unicode characters with BufferedReader or PrintWriter
I am creating a pretty standard chat server and client with the exception that I want to be able to send special math symbols back and forth to aid in helping people with math homework. The unicode characters will appear on the buttons, in the textField (where users type in their messages), in the messageArea (where users see all of the messages) correctly. However, as soon as the server reads it, it is converted to a ? character by either the BufferedReader or the PrintWriter, but I am fairly certain it is the BufferedReader. All of the Sun examples I have read recommend doing exactly what I have done to be able to support unicode characters so I am somewhat at a loss. Any help would be appreciated. I will include all of the source code (which is rather large) but the main problem is the with the BufferedReader or PrintWriter when the servers reads the string in and then broadcasts it to all the clients (at least I'm pretty sure it is).
// ChatServer.java
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
* A multithreaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
* 2. The server should do some logging.
public class ChatServer {
* The port that the server listens on.
private static final int PORT = 9001;
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
private static HashSet names = new HashSet();
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
private static HashMap writers = new HashMap();
private static HashMap userSockets = new HashMap();
private static Set keys;
* The appplication main method, which just listens on a port and
* spawns handler threads.
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
} catch (Exception e) {
} finally {
listener.close();
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
public Handler(Socket socket) {
this.socket = socket;
public void disconnect(String userName) {
if (userName != null) {
names.remove(userName);
if (writers.get(userName) != null) {
writers.remove(userName);
try {
((Socket)userSockets.get(userName)).close();
} catch (IOException e) {
e.printStackTrace();
System.out.println(userName +" has disconnected from the Chat Server.");
keys = writers.keySet();
for (Iterator i = keys.iterator(); i.hasNext(); ) {
((PrintWriter)writers.get(i.next())).println(
"USERQUIT" +name);
public void disconnectAll() {
for (Iterator i = names.iterator(); i.hasNext();) {
String userName = i.next().toString();
if (!userName.equals("administrator")) {
names.remove(userName);
keys = writers.keySet();
for (Iterator it = keys.iterator(); it.hasNext(); ) {
((PrintWriter)writers.get(it.next())).println(
"USERQUIT" +name);
writers.remove(userName);
userSockets.remove(userName);
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
public void run() {
try {
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Request a name from this client. Keep requesting until
// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
return;
synchronized (names) {
if (!names.contains(name) && name.equalsIgnoreCase("administrator")) {
out.println("SUBMITPASSWORD");
String password = in.readLine();
if (password.equals("s3cure")) {
out.println("GRANTEDADMIN");
if (!names.contains(name)) {
names.add(name);
break;
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
keys = writers.keySet();
for (Iterator i = keys.iterator(); i.hasNext(); ) {
((PrintWriter)writers.get(i.next())).println(
"USERJOIN" +name);
writers.put(name, out);
userSockets.put(name, socket);
System.out.println(name +" has successfully connected to the Chat Server.");
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
if (input == null) {
return;
else if (input.startsWith("LISTUSERS")) {
Iterator i = names.iterator();
String namesString = new String();
while (i.hasNext()) {
namesString += " " +i.next();
out.println("USERLIST " +namesString);
catch (Exception e) {
finally {
disconnect(name);
// ChatClient.java
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Point;
import java.awt.Button;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
//import javax.swing.JTextPane;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
* A simple Swing-based client for the chat server. Graphically
* it is a frame with a text field for entering messages and a
* textarea to see the whole dialog.
* The client follows the Chat Protocol which is as follows.
* When the server sends "SUBMITNAME" the client replies with the
* desired screen name. The server will keep sending "SUBMITNAME"
* requests as long as the client submits screen names that are
* already in use. When the server sends a line beginning
* with "NAMEACCEPTED" the client is now allowed to start
* sending the server arbitrary strings to be broadcast to all
* chatters connected to the server. When the server sends a
* line beginning with "MESSAGE " then all characters following
* this string should be displayed in its message area.
public class ChatClient {
BufferedReader in;
PrintWriter out;
JFrame frame = new JFrame("Math Chatter version 0.3");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(25, 40);
//JTextPane messageArea = new JTextPane();
// Menu
JMenuBar menuBar = new JMenuBar();
// File Menu and MenuItems
JMenu fileMenu = new JMenu();
JMenuItem connectMenuItem = new JMenuItem();
JMenuItem disconnectMenuItem = new JMenuItem();
JMenuItem exitMenuItem = new JMenuItem();
// Help Menu and MenuItems
JMenu helpMenu = new JMenu();
JMenuItem aboutMenuItem = new JMenuItem();
JOptionPane aboutDialog = new JOptionPane();
// Message Area Popup Menu and MenuItems
JPopupMenu messageAreaPopupMenu = new JPopupMenu();
JMenuItem connectPopupMenuItem = new JMenuItem();
JMenuItem disconnectPopupMenuItem = new JMenuItem();
JMenuItem clearTextMenuItem = new JMenuItem();
JMenuItem exitPopupMenuItem = new JMenuItem();
MouseListener messageAreaPopupListener = new messageAreaPopupListener();
// User Area Popup Menu and MenuItems
JPopupMenu userAreaPopupMenu = new JPopupMenu();
JMenuItem pingPopupMenuItem = new JMenuItem();
JMenuItem disconnectUserPopupMenuItem = new JMenuItem();
JMenuItem disconnectAllUsersPopupMenuItem = new JMenuItem();
MouseListener userAreaPopupListener = new userAreaPopupListener();
// Panel with textfield, send, and clear buttons
JPanel sendTextPanel = new JPanel();
// Panel that has all the math buttons
JPanel buttonPanel = new JPanel();
// Panel that has messageArea and users panell
JPanel displayPanel = new JPanel();
DefaultListModel listModel = new DefaultListModel();
JList userNamesList = new JList(listModel);
//JTextArea userNamesTextArea = new JTextArea(25, 10);
// buttonPanel stuff
Button sendButton = new Button();
Button clearButton = new Button();
Button infinityButton = new Button();
Button thetaButton = new Button();
Button limitButton = new Button();
Button thereforeButton = new Button();
JLabel buttonLabel = new JLabel("Useful math stuff: ");
HashSet usersHashSet = new HashSet();
LinkedList sentMessageList = new LinkedList();
ListIterator sentMessageIterator;
boolean isAdmin = false;
* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Return in the
* listener sends the textfield contents to the server. Note
* however that the textfield is initially NOT editable, and
* only becomes editable AFTER the client receives the NAMEACCEPTED
* message from the server.
public ChatClient() {
// -----------------> Layout MenuBar
frame.setJMenuBar(menuBar);
fileMenu.setText("File");
connectMenuItem.setText("Connect");
connectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showWhoopsDialog();
/*out.println("CONNECT");
try {
run();
catch (Exception ex) {
ex.printStackTrace();
fileMenu.add(connectMenuItem);
disconnectMenuItem.setText("Disconnect");
disconnectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chatDisconnect();
fileMenu.add(disconnectMenuItem);
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
System.exit(0);
return;
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText("Help");
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aboutDialog.setDoubleBuffered(true);
aboutDialog.showMessageDialog(frame,
"Chat Server and Client were originally written by Ray Toal and were found at \n http://www.technocage.com/~ray/viewsource.jsp?java/networking/ChatServer.java and \n http://www.technocage.com/~ray/viewsource.jsp?java/networking/ChatClient.java. \n\n Math Chatter and all revisions have been done by William Ready.",
"About Math Chatter Server and Client version 0.3",
JOptionPane.INFORMATION_MESSAGE);
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
// -----------> End Menu
// -----------> Popup Menus
// -----------> Message Area Popup Menu
connectPopupMenuItem.setText("Connect");
connectPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showWhoopsDialog();
disconnectPopupMenuItem.setText("Disconnect");
disconnectPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chatDisconnect();
clearTextMenuItem.setText("Clear text");
clearTextMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
messageArea.setText("");
exitPopupMenuItem.setText("Exit");
exitPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
System.exit(0);
messageAreaPopupMenu.add(connectPopupMenuItem);
messageAreaPopupMenu.add(disconnectPopupMenuItem);
messageAreaPopupMenu.add(clearTextMenuItem);
messageAreaPopupMenu.add(exitPopupMenuItem);
messageArea.addMouseListener(messageAreaPopupListener);
// -----------> End Message Area Popup Menu
// -----------> User Area Popup Menu
pingPopupMenuItem.setText("Ping User");
pingPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.out.println("Yo yo yo");
disconnectUserPopupMenuItem.setText("Disconnect User");
disconnectUserPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (userNamesList.getSelectedValue() != null) {
//System.out.println("Yo yo yo");
out.println("DISCONNECTUSER " +userNamesList.getSelectedValue().toString());
//disconnectUserPopupMenuItem.setEnabled(false);
disconnectUserPopupMenuItem.setVisible(false);
disconnectAllUsersPopupMenuItem.setText("Disconnect All Users");
disconnectUserPopupMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (userNamesList.getSelectedValue() != null) {
//System.out.println("Yo yo yo");
out.println("DISCONNECTALLUSERS");
//disconnectUserPopupMenuItem.setEnabled(false);
disconnectAllUsersPopupMenuItem.setVisible(false);
userAreaPopupMenu.add(pingPopupMenuItem);
userAreaPopupMenu.add(disconnectUserPopupMenuItem);
userAreaPopupMenu.add(disconnectAllUsersPopupMenuItem);
userNamesList.addMouseListener(userAreaPopupListener);
// -----------> End User Area Popup Menu
// -----------> End Popup Menus
// -----------> Layout GUI
textField.setEditable(false);
textField.requestDefaultFocus();
messageArea.setEditable(false);
sendTextPanel.setLayout(new FlowLayout());
sendTextPanel.add(textField);
sendButton.setLabel("Send");
sendButton.setEnabled(false);
sendTextPanel.add(sendButton);
clearButton.setLabel("Clear");
sendTextPanel.add(clearButton);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(buttonLabel);
infinityButton.setLabel("\u221e");
buttonPanel.add(infinityButton);
thetaButton.setLabel("\u03b8");
buttonPanel.add(thetaButton);
limitButton.setLabel("lim");
buttonPanel.add(limitButton);
thereforeButton.setLabel("\u2234");
buttonPanel.add(thereforeButton);
userNamesList.setVisibleRowCount(26);
userNamesList.setFixedCellWidth(110);
JScrollPane nameTextScrollPane = new JScrollPane(userNamesList);
JScrollPane messageAreaScrollPane = new JScrollPane(messageArea);
displayPanel.setLayout(new FlowLayout());
displayPanel.add(messageAreaScrollPane);
displayPanel.add(nameTextScrollPane);
frame.getContentPane().add(sendTextPanel, "North");
frame.getContentPane().add(displayPanel, "Center");
frame.getContentPane().add(buttonPanel, "South");
frame.pack();
// ---------------> Add Listeners
textField.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e){ }
public void keyTyped(KeyEvent e){
if (e.getKeyChar() == KeyEvent.VK_UP) {
if (sentMessageIterator.hasNext()) {
textField.setText((String)sentMessageIterator.next());
if (e.getKeyChar() == KeyEvent.VK_DOWN) {
if (sentMessageIterator.hasPrevious()) {
textField.setText((String)sentMessageIterator.previous());
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
String text = textField.getText();
if (text != null && !(text.equals(""))) {
sentMessageList.addFirst(textField.getText());
sentMessageIterator = sentMessageList.listIterator();
out.println(textField.getText());
textField.setText("");
public void keyReleased(KeyEvent e){}
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
textField.requestFocus();
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.requestFocus();
infinityButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() +"\u221e");
textField.requestFocus();
thetaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() +"\u03b8");
textField.requestFocus();
limitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String limit = JOptionPane.showInputDialog(frame,
"Enter the value that the variable approaches. \n If the value is infinity, type in inf. \n (Note: the variable name is irrelevant)",
"Value that variable approaches",
JOptionPane.QUESTION_MESSAGE);
if (limit != null && limit.equalsIgnoreCase("inf"))
textField.setText(textField.getText() +"lim [x->\u221e] ");
else if (limit != null)
textField.setText(textField.getText() +"lim [x->" +limit +"] ");
textField.requestFocus();
thereforeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() +"\u2234");
textField.requestFocus();
// -------------> End Listeners
// -------------> End GUI
* Prompt for and return the address of the server.
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"Welcome to the Chatter",
JOptionPane.QUESTION_MESSAGE);
private void showWhoopsDialog() {
JOptionPane.showMessageDialog(frame,
"Unfortunately this feature has not been implemented yet. \n The only way to connect currently is to exit the program \n and start it again",
"Whoops!",
JOptionPane.ERROR_MESSAGE);
private void chatDisconnect() {
messageArea.append("You have disconnected from the Chat Server\n");
textField.setEditable(false);
messageArea.setEnabled(false);
userNamesList.setEnabled(false);
fileMenu.requestFocus();
out.println("DISCONNECT");
* Prompt for and return the desired screen name.
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
private String getPassword() {
return JOptionPane.showInputDialog(
frame,
"Type in your password:",
"Password Input",
JOptionPane.PLAIN_MESSAGE);
* Connects to the server then enters the processing loop.
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
if (serverAddress != null && !(serverAddress.equals(""))) {
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
try {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
out.println("LISTUSERS");
sendButton.setEnabled(true);
//messageArea.setEnabled(true);
} else if (line.startsWith("SUBMITPASSWORD")) {
out.println(getPassword());
} else if (line.startsWith("GRANTEDADMIN")) {
isAdmin = true;
//disconnectUserPopupMenuItem.setEnabled(true);
disconnectUserPopupMenuItem.setVisible(true);
disconnectAllUsersPopupMenuItem.setVisible(true);
} else if (line.startsWith("DISCONNECT")) {
sendButton.setEnabled(false);
return;
} else if (line.startsWith("USERLIST")) {
StringTokenizer st = new StringTokenizer(line.substring(8), " ");
while (st.hasMoreTokens()) {
usersHashSet.add(st.nextToken());
listModel.removeAllElements();
for (Iterator i = usersHashSet.iterator(); i.hasNext(); ) {
listModel.addElement(i.next());
} else if (line.startsWith("USERJOIN")) {
String userJoinName = line.substring(8).trim();
usersHashSet.add(userJoinName);
listModel.addElement(userJoinName);
} else if (line.startsWith("USERQUIT")) {
String userQuitName = line.substring(8).trim();
usersHashSet.remove(userQuitName);
listModel.removeElement(userQuitName);
} else if (line.startsWith("MESSAGE")) {
messageArea.setFont(new Font("Lucida Sans", Font.PLAIN, 12));
messageArea.append(line.substring(8) + "\n");
catch (Exception e) {
//e.printStackTrace();
return;
* Runs the client as an application with a closeable frame.
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setLocation(200, 100);
client.frame.show();
client.run();
class messageAreaPopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
messageAreaPopupMenu.show(e.getComponent(),
e.getX(), e.getY());
class userAreaPopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
userAreaPopupMenu.show(e.getComponent(),
e.getX(), e.getY());Yes, the code is large, isn't it. It is a good idea, when you have a problem you can't solve, to remove unnecessary code. When the problem disappears, then you know the code you just removed was probably the source of the problem.
But in your case, I think that none of the 1000 lines of code you posted are the problem. You appear to be using Lucida Sans, which is a positive sign; it can render many of the characters you have hard-coded in your program. But apparently the problem is with characters that are coming from somewhere else? And you are using a PrintWriter to send them there and a BufferedReader to get them back? These convert your data from characters to bytes and back again using the default encoding for your system. Chances are that this encoding is some "extended ASCII" encoding that doesn't know how to map anything above \u00ff. You need to get an InputStreamReader and an OutputStreamWriter into your transmission. (Wrap your socket.getInputStream() in an InputStreamReader and wrap that in a BufferedReader, etc.) These objects can take an encoding name as their second parameter; try "UTF-8" or "UTF8" for the encoding. Their API documentation has a link to a page about encodings; follow that if you need more info. -
BufferedReader's readLine() method problem (REPOST)
Hello,
If anyone can help me out I would not have to struggle :)
Here is the thing. I have a file like this:
1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniui yjpeppaezftgjfviwxunu
2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohe njixwufcdlbjlkoqevqdy
3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzg iefgarenbxnxtxnqdqpfh
4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifph tldawxsfepotkgqqsivur
5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycr xdhnhxyitkeqynedrbroh
6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyz apcinhjyysxsdwfjugndr
7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfid xyoktwupsuqbqgnxdfbze
8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpku uttidlnqftdnzqpqafels
9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbn bnrflotpqytqzbgnkeyrk
10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofb xfsynlxhyuvqprqbvoruk
and my java programs is like this:
public String searchForAString(String fileName, int lineNumber)
File fileObject = new File(fileName);
String finalString ="";
String record = "";
int line;
try
FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
//DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
//System.out.println(bufferedReaderObject.readLine());
//System.out.println("_____________________");
while((bufferedReaderObject.readLine()) != null)
System.out.println(bufferedReaderObject.readLine());
Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!
Re: BufferedReader's readLine() method problem.
Author: EagleEye101 Feb 18, 2005 8:48 PM (reply 1 of 1)
You do relize that when you call the in.readLine() in your loop conditional and in your loop body it reads in diffrent lines. Try this:
public String searchForAString(String fileName, int lineNumber)
File fileObject = new File(fileName);
String finalString ="";
String record = "";
int line;
try
FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
//DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
//System.out.println(bufferedReaderObject.readLine());
//System.out.println("_____________________");
String s = bufferedReaderObject.readLine();
while(s != null)
System.out.println(bufferedReaderObject.readLine());
s = bufferedReaderObject.readLine();
Every time you call the readLine method, it does read a diffrent line. Java does not know you want to read the same line twice.
Tried it, did not work. I need to go through each line of the file I have. Any ideas?solution should be in your other thread.
Please do not repeat threads--it really bugs the people here, just some 'nettiquite' --I don't mean to be a grouch.
--later. : ) -
BufferedReader - ready() problem
hi folks,
I ' m using the following code:
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
System.out.println(in.ready());
if (in.ready())
int input=in.read();
char inchar=(char)input;
inchar=character.toLowerCase(inchar);
.......and have the following problem:
in.ready() always returns false, so that it is impossible to read the char entered by the user. On the other hand, if I use the code without in.ready(), I get a synchronized (lock) {} IOException!
May be somebody can tell me how to read a users input successfully,
Thanx in advance,
macmoDoesn't in.read() block until something has been entered? From the API docs of Reader:
"This method will block until a character is available, an I/O error occurs, or the end of the stream is reached." In the case of System.in, it's quite improbable that the two latter ones occur... :)
So, what you want should be simplyBufferedReader in =new BufferedReader(new InputStreamReader(System.in));
char inchar=Character.toLowerCase((char)input); -
Dukes for BufferedReader Hanging Problem
Hi,
I have an assignment I'm working on, and I've hit a road block; We're basically writing our own proxy server to handle GET calls for txt and .ps files respectively.
My problem is that after I've connected to a server, i.e. Geocities, I send the message I recieved from my browser and then I wait for a reply. The problem is I end up waiting until my connection to the server times out.
I've tried the following:
Looping around until the BufferedReader.ready() = true;
and
Waiting on the readLine()
and
Trying to do just a read() as well
Any help would be greatly appreciated! Thank you for your time!
Also as a side note , so I don't get chewed out for sillyness, we're only allowed to use sockets and serversockets, no classes that start with URL.
Here's the code for sending and recieving as well as my output:
=================================================================================
System.out.println("Trying to Send Request to : " + location);
for (int i = 0; i < request.length; i++)
try
System.out.println("\tSending: " + request);
outstream.writeBytes(request[i] + "\n");
} catch (Exception e) { System.out.println("Error: Message Line #"+i+" couldn't be sent: " + e); }
try
System.out.println("Trying to Get Response from attached Location:" + location);
my_message = instream.readLine(); //Hangs Here
if (my_message != null)
while(my_message != null)
System.out.println("\t"+ my_message);
full_message += my_message + "\n";
my_message = instream.readLine();
reply = full_message.split("\n");
} catch (Exception e) { System.out.println("Error Recieving Response from " + location + ": "+e); }
return reply;
===============================================================================
Output:
Incoming Request from XXX.XXX.XXX.XXX
-->GET http://www.geocities.com/shotgunmoose/wife.txt HTTP/1.0
-->Host: www.geocities.com
-->User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1
-->Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
-->Accept-Language: en-us,en;q=0.5
-->Accept-Encoding: gzip,deflate
-->Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
-->Keep-Alive: 300
-->Proxy-Connection: keep-alive
Connected to location : www.geocities.com
Trying to Send Request to : www.geocities.com
Sending: GET http://www.geocities.com/shotgunmoose/wife.txt HTTP/1.0
Sending: Host: www.geocities.com
Sending: User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1
Sending: Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Sending: Accept-Language: en-us,en;q=0.5
Sending: Accept-Encoding: gzip,deflate
Sending: Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Sending: Keep-Alive: 300
Sending: Proxy-Connection: keep-alive
Trying to Get Response from attached Location:www.geocities.com
Error Recieving Response from www.geocities.com: java.net.SocketException: Connection resetNever Mind, problem solved;
I wasn't finishing the HTTP GET with 2 consecutive newlines!
Let this post be a lesson to all.. read the api's carefull. -
Strange problem with BufferedReader
Hi
I am facing a very strange problem in the code below. My motive is to check a particular word in a file which contains very large number of words more than 100000. In the code below the string Word1 contains the word which is to be searched in the file.
void checkForWord()
char[]word = new char[6];
String Word = "Start";
BufferedReader reader = null;
boolean present =false;
int temp = lineValue1[currentlineValue-1];
int j=0;
for(int i=0;i<temp;i++)
int temp1= lineSelector[lineNumber];
word[j] = board1.letterBoardRack[temp1].values;
System.out.println(" lineNumber the char "+lineNumber+" "+ word[j]);
j++;
Word = new String(word);
String Word1 = Word.toLowerCase();
Word1.trim();//////////////////word to be searched
System.out.println(" The change "+Word1);
String line ="start";
//////////////////////////Perfect till this point/////////////////////////////
try
reader = new BufferedReader(new FileReader(inputFile));
while((line = reader.readLine())!= null )
///line is getting printed properly if i am using System command here to see it
line = line.trim();
if(line.equals(Word1))
present=true;
System.out.println("The word found "+ Word1);//////not printing it inspite of its presence
break;
System.out.println(" not in dict");////////////////////not printing it for unknown reasons
reader.close();
catch(IOException e){ System.out.println("The exception ");}
System.out.println(" The word "+ Word + present); ///////Not printing it
Now inspite of that word being present there in the file the System.out.println command is not executing(please see the code). Even after finishing off the loop the System command is not executing and the control is directly getting back to the calling point. What could be the problem? Am i doing something wrong. Shall i use some other reader. please help!!!!!!!!!!!!!!!!
Thanx in advance
Sushanthi i have tried string tokenizer also but of no use
while((line = reader.readLine())!= null )
StringTokenizer st = new StringTokenizer(line);
//String line1 = line.toString();
// line.indexOf(Word1);
while (st.hasMoreTokens()) {
if(st.nextToken().equals(Word1))
present=true;
System.out.println("The word found "+ Word1);
break;
}//end of first while
}//end of second while
What could be the problem? -
Problems in Read a file using BufferedReader
i wrot the follwing code to search for a word in a list of files
when i compile it ,it does not give me any error , but at run it give me the following Eception:
java.io.FileNotFoundException: home.html (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at webSearchServlet.readFile(webSearchServlet.java:111)
at webSearchServlet.doGet(webSearchServlet.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at desisoft.server.servlets.Servlet.service(Servlet.java:86)
at desisoft.server.servlets.Servlet.doService(Servlet.java:62)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.lang.String.*;
public class webSearchServlet extends HttpServlet{
String[] path;
PrintWriter out;
String search ;
int num = 0;
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException{
try {
Statement stmt;//used for database access
ResultSet rs;//used for database access
Connection conn;
//Set the content type of the data to be sent back
// to the client.
res.setContentType("text/html");
//Get an output writer object to send data back to
// the client.
out= res.getWriter();
//Begin constructing the HTML page to send back to
// the client.
out.println("<HTML>");
out.println("<HEAD><TITLE>Search </TITLE></HEAD>");
out.println("<BODY>");
//Register the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Construct URL for database on node3
String url = "jdbc:odbc:search";
String username="";
String password="";
//Get a connection to the database
conn = DriverManager.getConnection(url,username,password);
//Get a Statement object
stmt = conn.createStatement();
search = req.getParameter("search");
//Create a statement object linked to the database
// connection.
stmt = conn.createStatement();
//Use the statement object to execute a query on the
// database.
String query = "SELECT Path FROM searchTable";
rs = stmt.executeQuery(query);
ResultSetMetaData resultSetMetaData =
rs.getMetaData();
int numColumns = resultSetMetaData.getColumnCount();
path = new String[numColumns];
while (rs.next()) {
path[num] = rs.getString("Path");
num++;
String[] result = searchString(search ,num);
conn.close();
catch(Exception e){e.printStackTrace();}
for (int i=0 ; i<path.length ;i++){
String output = readFile(path[i] ,search);
if(output == "yes"){
out.println("<h2>The word you search for <i>"+search
+"</i> was found in the file <i>"+path[i]+"</i></h2><br>");
else
out.println("<h2>The word you search for <i>"+search
+"</i> was <b>NOT<b> found in the file <i>"+path[i]+"</i></h2><br>");
/* a method to test the quary string of the user
*it tack a String value and return a String array.
public String[] searchString(String str , int numberOfFiles) {
String[] strArray =new String[numberOfFiles];
int indexOfPlus = str.indexOf('+');
if (indexOfPlus == -1) {
strArray[0] = str;
return strArray;
else {
String firstWord = str.substring(0 ,indexOfPlus-1);
String secondWord = str.substring(indexOfPlus-1);
strArray[0] = firstWord;
strArray[1] = secondWord;
return strArray;
public String searchFile(String stringLine ,String word){
int index = stringLine.indexOf(word);
if (index == -1) return "no";
else
return "yes";
public String readFile (String fileName ,String word) throws IOException ,RuntimeException ,NullPointerException
,FileNotFoundException {
//Read input by lines
FileReader fr = new FileReader(fileName);
BufferedReader in = new BufferedReader (fr);
String s1,s2 = new String();
while ((s1 = in.readLine()) != null ) {
s2 = searchFile(s1,word);
if (s2 == "yes") break;
else
s2="no";
fr.close();
in.close();
if (s2 == "yes") return "yes";
else
return "no";
what is the wrong???
shimaaYou already have posted the answer:
java.io.FileNotFoundException: home.html (The system cannot find the file specified)If you are only using "filename" for creating BufferedReader the file will be expected in the working directory of runnig application.
Your application is the server, 'cause servlet uses servers context.
But this will hardly be the directory for your *.html. So you have to add the path of the directory where your files are placed. (Absolute or relative to current working directory.) "path/filename"
I don't know anything about your directory structure, you will have to find out by yourself. -
BufferedReader's readLine() method problem.
Hello,
If anyone can help me out I would not have to struggle :)
Here is the thing. I have a file like this:
1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniuiyjpeppaezftgjfviwxunu
2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohenjixwufcdlbjlkoqevqdy
3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzgiefgarenbxnxtxnqdqpfh
4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifphtldawxsfepotkgqqsivur
5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycrxdhnhxyitkeqynedrbroh
6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyzapcinhjyysxsdwfjugndr
7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfidxyoktwupsuqbqgnxdfbze
8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpkuuttidlnqftdnzqpqafels
9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbnbnrflotpqytqzbgnkeyrk
10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofbxfsynlxhyuvqprqbvoruk
and my java programs is like this:
public String searchForAString(String fileName, int lineNumber)
File fileObject = new File(fileName);
String finalString ="";
String record = "";
int line;
try
FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
//DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
//System.out.println(bufferedReaderObject.readLine());
//System.out.println("_____________________");
while((bufferedReaderObject.readLine()) != null)
System.out.println(bufferedReaderObject.readLine());
Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!You do relize that when you call the in.readLine()in
your loop conditional and in your loop body itreads
in diffrent lines. Try this:
public String searchForAString(String fileName,int
lineNumber)
File fileObject = new File(fileName);
String finalString ="";
String record = "";
int line;
try
FileInputStream fileInputStreamObject = new
FileInputStream(fileObject);
BufferedInputStream bufferedInputStreamObject =new
BufferedInputStream(fileInputStreamObject);
//DataInputStream dataInputStreamObject = new
DataInputStream(bufferedInputStreamObject);
BufferedReader bufferedReaderObject = new
BufferedReader(new
InputStreamReader(bufferedInputStreamObject));
//System.out.println(bufferedReaderObject.readLine());
//System.out.println("_____________________");
String s = bufferedReaderObject.readLine();
while(s != null)
System.out.println(bufferedReaderObject.readLine());
s = bufferedReaderObject.readLine();
Every time you call the readLine method, it doesread
a diffrent line. Java does not know you want toread
the same line twice.Err, shouldn't that be:
while(s != null)
System.out.println(s);
s = bufferedReaderObject.readLine();
Otherwise, you're still discarding a line if you use
two readLines in the while loop.yes you are correct... srry late last night and I wsa copying his code :). -
SSLSocket BufferedReader blocking problem
I have a client program which connects to an Apache server, sends some HTTP messages and retrieves the responses.
An example message is:
OPTIONS / HTTP/1.1
Host: 127.0.0.1
Accept: */*The response from Apache is:
HTTP/1.1 200 OK
Date: Wed, 07 Mar 2007 14:57:16 GMT
Server: Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.8a DAV/2
DAV: 1,2
DAV: <http://apache.org/dav/propset/fs/1>
MS-Author-Via: DAV
Allow: OPTIONS,GET,HEAD,POST,DELETE,TRACE,PROPFIND,PROPPATCH,COPY,MOVE,LOCK,UNLOCK
Content-Length: 0
Content-Type: httpd/unix-directoryThis is the code that gets the response from Apache, the in variable is a BufferedReader connected to the InputStream of the SSLSocket.
private String getResponse() throws IOException {
String response = "";
int c = in.read();
char ch;
long start = System.currentTimeMillis();
while (in.ready() && c != -1) {
ch = (char) c;
response += ch;
c = in.read();
long finish = System.currentTimeMillis();
System.out.println(finish - start);
ch = (char) c;
response += ch;
return response;
}The output to the console is how long it took to get the whole message from the InputStream. In HTTP (Socket) mode this number is between 0-20 milliseconds but when i use HTTPS (SSLSocket) mode it is approx 5000! This number is independent of the time it takes to handshake with the server.
In SSL mode the above method fails actually, because in.ready() returns false the first time, instead i have to modify it to:
while ((c = in.read()) != -1) {
ch = (char) c;
response += ch;
System.out.print(ch);
}In which case, i get the whole message printed to the console as fast as HTTP mode but on the final evaluation of in.read() it takes the previously stated 5000 ms to finally exit the loop and return the String response.
I am certain my Apache server is configured correctly as if i use a web browser to navigate the site in HTTPS the response is instant as like in unsecure HTTP mode.
So why am i seeing this 5000 ms delay, when i reach the end of the stream in the BufferedReader?
There should be no difference in reading the BufferedReader when using either HTTP or HTTPS mode, given that i've accounted for the time it takes to handshake, right?The final evaluation of in.read() happens at EOF which requires an SSL close_notify message to be exchanged in both directions, which takes a finite non-zero time.
5 seconds does seem excessive though. Are you using HttpsURLConnection, or an SSLSocket directly? If you're using HttpsURLConnection (or an https: URL) you could read until you've got the entire content-length instead of reading to EOF, or you could try setting the Connection header to 'close' before you get any streams from the URLConnection. I'm thinking that maybe the web server is keeping the connection alive for 5 seconds and you're just blocked in the read waiting for that. -
BufferedReader argument problem
I am getting one error with BufferedReader. Here is the code and below it is the error. If anyone can explain, I would appreciate it:
import java.io.*;
import java.util.StringTokenizer;
public class Socks {
public static void main(String args[])
int numberOfsocks = 0;
int numberOfpairs = 0;
String line, sockColor, sockType;
StringTokenizer tokenizer;
try
FileReader fr = new FileReader(args[1]);
catch(FileNotFoundException e)
System.out.println("File Not Found or no File Specified");
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
while(line != null)
tokenizer = new StringTokenizer(line);
sockColor = tokenizer.nextToken();
sockType = tokenizer.nextToken();
System.out.println(sockColor);
System.out.println("\n");
System.out.println(sockType);
System.out.println("\n");
line = inFile.readLine();
inFile.close();
Here is the error:
C:\Socks\Socks.java:23: cannot resolve symbol
symbol : variable fr
location: class Socks
BufferedReader inFile = new BufferedReader(fr);
^
1 error
Process completed.A scope issue.
A variable can only be referenced within the block in which it is declared. As you have declared and initialised object fr within the try block then you cannot reference it outside of here. Try this:
try
FileReader fr = new FileReader(args[1]);
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
while(line != null)
tokenizer = new StringTokenizer(line);
sockColor = tokenizer.nextToken();
sockType = tokenizer.nextToken();
System.out.println(sockColor);
System.out.println("\n");
System.out.println(sockType);
System.out.println("\n");
line = inFile.readLine();
} // end try block
catch(FileNotFoundException e)
System.out.println("File Not Found or no File Specified");
catch (IOException ioe)
} -
Problem with threads running javaw
Hi,
Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
troy.troy,
Try and post a minimum code sample of your app which
does not work.
When using javaw, make sure you redirect the standard
error and standard output streams to file.
Graeme.Hi Graeme,
I dont understand what you mean by redirection to file? some of my code below.
The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
public class Server{
ServerSocket aServerSocket;
Socket dianosticsSocket;
Socket nPortExpress;
ClientListener aClientListener;
LinkedList queue = new LinkedList();
int port = 0;
int clientPort = 0;
String clientName = null;
boolean serverAlive = true;
* Server constructor generates a server
* Socket and then starts a client threads.
* @param aPort socket port of local machine.
public Server(int aPort, String aClientName, int aClientPort){
port = aPort;
clientName = aClientName;
clientPort = aClientPort;
try{
// create a new thread
aServerSocket = new ServerSocket(port) ;
// connect to the nPortExpress
aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
// aClientListener.setDaemon(true);
aClientListener.start();
// start a dianostic port
DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
// System.out.println("Server is running on port " + port + "...");
// System.out.println("Connect to nPort");
catch(Exception e)
// System.out.println("ERROR: Server port " + port + " not available");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
serverAlive = false;
System.exit(1);
while(serverAlive&&aClientListener.hostSocket.isConnected()){
try{
// connect the client
Socket aClient = aServerSocket.accept();
//System.out.println("open client connection");
//System.out.println("client local: "+ aClient.getLocalAddress().toString());
// System.out.println("client localport: "+ aClient.getLocalPort());
// System.out.println("client : "+ aClient.getInetAddress().toString());
// System.out.println("client port: "+ aClient.getLocalPort());
// make a new client thread
ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
// start thread
clientThread.start();
catch(Exception e)
//System.out.println("ERROR: Client connection failure");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
}// end while
} // end constructor Server
void serverExit(){
JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}// end class Server
*** connect to another server
public class ClientListener extends Thread{
InetAddress hostName;
int hostPort;
Socket hostSocket;
BufferedReader in;
PrintWriter out;
boolean loggedIn;
LinkedList queue; // reference to Server queue
Server serverRef; // reference to main server
* ClientListener connects to the host server.
* @param aHostName is the name of the host eg server name or IP address.
* @param aHostPort is a port number of the host.
* @param aLoginName is the users login name.
public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer) // reference to Server queue)
hostName = aHostName;
hostPort = aHostPort;
queue = aQueue;
serverRef = aServer;
// connect to the server
try{
hostSocket = new Socket(hostName, hostPort);
catch(IOException e){
//System.out.println("ERROR: Connection Host Failed");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} // end constructor ClientListener
** multi client connection server
ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
queue = aQueue;
addToQueue(this);
client = aSocket;
clientRef = aClientListener;
aDiagnostic = diagnostics;
} // end constructor ClientWorker
* run method is the main loop of the server program
* in change of handle new client connection as well
* as handle all messages and errors.
public void run(){
boolean alive = true;
String aSubString = "";
in = null;
out = null;
loginName = "";
loggedIn = false;
while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
if(aDiagnostic){
out.println("WELCOME to diagnostics");
broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
out.flush();
else {
out.println("WELCOME to Troy's Server");
broadCastDia("Connect : client "+client.getInetAddress().toString());
out.flush();
String line;
while(((line = in.readLine())!= null)){
StringTokenizer aStringToken = new StringTokenizer(line, " ");
if(!aDiagnostic){
broadCastDia(line);
clientRef.sendMessage(line); // send mesage out to netExpress
out.println(line);
out.flush();
else{
if(line.equals("GETIPS"))
getIPs();
else{
clientRef.sendMessage(line); // send mesage out to netExpress
out.println(line);
out.flush();
} // end while
catch(Exception e){
// System.out.println("ERROR:Client Connection reset");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);
try{
if(aDiagnostic){
broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
out.flush();
else {
broadCastDia("Disconnect : client "+client.getInetAddress().toString());
out.flush();
// close the buffers and connection;
in.close();
out.close();
client.close();
// System.out.println("out");
// remove from list
removeThreadQueue(this);
alive = false;
catch(Exception e){
// System.out.println("ERROR: Client Connection reset failure");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);
}// end while
} // end method run
* method run - Generates io stream for communicating with the server and
* starts the client gui. Run also parses the input commands from the server.
public void run(){
boolean alive = true;
try{
// begin to life the gui
// aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
// aGuiClient.show();
in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
while (alive && hostSocket.isConnected()){
String line;
while(((line = in.readLine())!= null)){
System.out.println(line);
broadCast(line);
} // end while
} // end while
catch(Exception e){
// System.out.println("ERRORa Connection to host reset");
JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
try{
hostSocket.close();
}catch(Exception a){
JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
alive = false;
System.exit(1);
} // end method run
Maybe you are looking for
-
Will Acrobat 9.5.2 run under Windows 8?
Transferred from Win 7 via PC Mover. Printer did not transfer so I reinstalled from original CD. When trying to print a Word doc, get error message in Printer box in Devices and Printers. No explanation of error.
-
Lion Crashing to Black - Kernel Error Included
Hey, Loving Lion so far - but... When I'm away from the computer I seem to get this message a lot. As I've never had it while sat at a machine I can't vouch for what causes it, but it might be something to do with me transferring to my NAS via WiFi.
-
WL 6 on NT as a Service - how to modify classpath
We want to modify the classpath of WebLogic to include classes of other products we use (like SpatialFX) so our server programs can get to them. Since we have WL running as a service how do we do this - short of uninstalling the service, modifying th
-
Need gudence for MDM Certification
Hi All, I am New to MDM and have experience in XI. I am planning to write certification on MDM. I would request to suggest me to prvide any TBT's which are required for certification. Appreciate your help. Regards, Chandra.
-
SAP Data Archival Project Documentation Report
hi, Do any one can send me the documentation report on Data Archival .It ll be more helpful 2 me...Plz send me ASAP... Thanx in advance..