SimpleDateFormat format() method returning string as ??/??/????
private String dateTimeFormat(Long time) {
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
if (time != null) {
Date date = new Date(time);
return sf.format(date);
return null;
}Above function is returning date string as ??/??/???? ??:??:?? on particular system(LINUX-RHEL4). Its Default Locale is en_US.
What would be the problem ?
rathi123 wrote:
Tired running it locally,its working fine. I double checked locale settings of other machine (+locale+ command in Linux) it is also fine.
I want to know in which exceptional cases SimpleDateFormat format() method returns such (??/??/????) a string ?As I said, it doesn't (If I'm correct). It's more likely that you have an invalid encoding specified somewhere. What happens if you print the value into a log?
Similar Messages
-
Do Methods returning String create a String object in memeory and pass back the reference to the calling Method?
Thankshmm, i'll take a shot at answering your query - hope this meets your requirement ... Java does manipulate objects by reference, and all object variables are references. So when a method returns a String object (this object would be created within the scope of the method) the object reference is returned to the caller.
Now the point of confusion usually happens since, Java doesn't pass method arguments by reference; it passes them by value. Java passes object references by value as well. What this means is the references passed to the method are actually copies of the original references.Java copies and passes the reference by value, not the object. Thus, method manipulations on the object reference will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
Hope the above helps.
John Morrison -
Java Experts please help - SimpleDateFormat.format reduces date by a day !!
Hi,
I am facing a very weird problem with SimpleDateFormat class. The input Date to SimpleDateFormat.format method is getting reduced by ONE DAY. This problem is happening at random and is not reproducible at will. Any help/pointers to resolve this issue is very much appreciated !!.
Code is similar to the following code lines
input = "2003-11-01 00:00:00.000000000";
output = 31-Oct-2003 (strange !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
import java.util.TimeZone;
import java.util.SimpleTimeZone;
public class DateTester {
/** Default constructor for Util.
public DateTester() {
private static String replace(String pattern, String from, String to) {
return replace(pattern, from, to, null);
private static String replace(String pattern, String from, String to, String notFrom) {
StringBuffer sb = new StringBuffer();
boolean finished = false;
int index = pattern.indexOf(from);
if (index < 0) return pattern;
do {
if (notFrom == null ||
notFrom.length() + index > pattern.length() ||
!pattern.substring(index, index + notFrom.length()).equals(notFrom)) {
sb.append(pattern.substring(0, index));
sb.append(to);
sb.append(pattern.substring(index + from.length()));
finished = true;
} else index = pattern.indexOf(from, index + from.length());
while (!finished && index >= 0);
if (!finished) return pattern;
return sb.toString();
public static void main(String[] argv) {
String pattern = "DD-MON-YYYY";
System.out.println("original pattern =" + pattern);
pattern = replace(pattern, "FM", "");
pattern = replace(pattern, "AD", "G");
pattern = replace(pattern, "A.D.", "G");
pattern = replace(pattern, "BC", "G");
pattern = replace(pattern, "B.C.", "G");
pattern = replace(pattern, "AM", "a");
pattern = replace(pattern, "A.M.", "a");
pattern = replace(pattern, "PM", "a");
pattern = replace(pattern, "P.M.", "a");
pattern = pattern.replace('\"', '\t');
pattern = pattern.replace('\'', '\"');
pattern = pattern.replace('\t', '\'');
pattern = replace(pattern, "DDD", "DDD");
pattern = replace(pattern, "DAY", "dd");
pattern = replace(pattern, "DD", "dd", "DDD");
pattern = replace(pattern, "HH24", "HH");
pattern = replace(pattern, "HH12", "KK");
pattern = replace(pattern, "IW", "ww");
pattern = replace(pattern, "MI", "mm");
pattern = replace(pattern, "MM", "MM", "MMM");
pattern = replace(pattern, "MONTH", "MMMMM");
pattern = replace(pattern, "MON", "MMM");
pattern = replace(pattern, "SS", "ss");
pattern = replace(pattern, "WW", "ww");
pattern = replace(pattern, "W", "W");
pattern = replace(pattern, "YYYY", "yyyy");
pattern = replace(pattern, "YYY", "yyy");
pattern = replace(pattern, "YY", "yy");
pattern = replace(pattern, "Y", "y");
pattern = replace(pattern, "RRRR", "yyyy");
pattern = replace(pattern, "RRR", "yyy");
pattern = replace(pattern, "RR", "yy");
pattern = replace(pattern, "R", "y");
System.out.println("converted pattern =" + pattern);
String origDate = "2003-11-01 00:00:00.000000000";
System.out.println("original date =" + origDate);
Timestamp origTimeStamp = Timestamp.valueOf(origDate);
SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
sdf.setLenient(false);
String formattedDate = sdf.format((Date) origTimeStamp);
System.out.println("formatted date =" + formattedDate);
Thanks a lot for your time !Your code is too hard to read for me to look at it in great detail. When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.
However, I'm guessing it's a TimeZone issue. The midnight on 11/1 that you're setting is probably getting converted to GMT somewhere before the Date object is created. If you're in the U.S., then that's afternoon or evening on 10/31.
Try:
* Starting with a time that's later in the day on 11/1.
* Formatting your date to include time and timezone when you print it. (Just for testing--you can put it back once you understand what's going on
* Reading the Calendar, Timzone, Date, etc. APIs closely.
* Reading any tutorials or texts you can find on the subject.
* Writing a bunch of very small and simple tests to get an understanding of how this all fits together.
Date/Time/TZ handling in Java is kinda tricky. -
Need help in the String Format method
really need help in string.Format method. I would like to show the s in two digit numbers.
for example:
if s is below 10 then display *0s*
the expecting result is 01,02,03.. 09,10,11....
I tried this method, somehow i got the errors msg. pls advise. thx.
public void setDisplay(String s) {
String tmpSS=String.format("%02d",s);
this.ss.setText(tmpSS);
Edited by: bluesailormoon on May 19, 2008 10:30 AMApparently, you expect the string to consist of one or two digits. If that's true, you could do this:String tmpSS = (s.length() == 1) ? ("0" + s) : s; or this: String tmpSS = String.format("%02d", Integer.parseInt(s));
-
Find(String pkey) method returns multiple object of the same row
I'm not quite sure what i've done or havent done, but I've implemented updating a row using the em.persist(Object) method.....works great, but after i did that a few times the find(String pkey) method returns multiple copies of 1 row in the db
here are two rows in the db
personid(PK) firstName lastName
1234 joe jones
2345 rachel jones
when i execute any query looking for people with the last name jones, ie
select object(p) from Person p where p.lastName='jones'
it returns multiple objects of each row ie
1234 joe jones
1234 joe jones
1234 joe jones
1234 joe jones
2345 rachel jones
2345 rachel jones
2345 rachel jones
2345 rachel jones
There is only one row for both rachel and joe in the db, but why is the entity manager returning multiple objects of each, and how do i prevent that without using DISTINCT?
Thanks for the help in advanceSorry, i forgot to mention i'm using ejb 3 and jboss
-
EJB method returns 2D String array
Hi,
one of EJB method returns a 2 dimensional array of String. Is it okay? Is this a good EJB programming practice?
Thanks
SabirIts ok. but not consdered as best practice now.
Check out the DTO pattern(previously called value obects from sun's site.
--Ashwani -
Native method with String return type
Hi
i am implementing a Native method with String Return type.
i am able call the respective C++ method and my C++ method is printing the String (jstring in c++ code ) correctly
i but i am getting nullpointerexcepti while loading the string in to my Java String .
i am sure my java code calling the C++ code beacause my C++ code is printing the value and one more wonder is after the NPE my c++ code able to print the value
the code follows
HelloWorld.java
public class HelloWorld {
private native String print();
static {
System.loadLibrary("HelloWorld");
public static void main(String[] args) throws InterruptedException,NullPointerException{
HelloWorld hW= new HelloWorld();
for(int i=0;;i++){
String str= new HelloWorld().print();
System.out.println(str);
Thread.sleep(10000);
}and HelloWorld.cpp
// HelloWorld.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "jni.h"
#include <stdio.h>
#include "HelloWorld.h"
#include <windows.h>
#include "tchar.h"
#include "string.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
CHAR cpuusage(void);
typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;
static HMODULE s_hKernel = NULL;
void GetSystemTimesAddress()
if( s_hKernel == NULL )
s_hKernel = LoadLibrary(_T("Kernel32.dll"));
if( s_hKernel != NULL )
s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress( s_hKernel, "GetSystemTimes" );
if( s_pfnGetSystemTimes == NULL )
FreeLibrary( s_hKernel ); s_hKernel = NULL;
// cpuusage(void)
// ==============
// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
CHAR cpuusage()
FILETIME ft_sys_idle;
FILETIME ft_sys_kernel;
FILETIME ft_sys_user;
ULARGE_INTEGER ul_sys_idle;
ULARGE_INTEGER ul_sys_kernel;
ULARGE_INTEGER ul_sys_user;
static ULARGE_INTEGER ul_sys_idle_old;
static ULARGE_INTEGER ul_sys_kernel_old;
static ULARGE_INTEGER ul_sys_user_old;
CHAR usage = 0;
// we cannot directly use GetSystemTimes on C language
/* add this line :: pfnGetSystemTimes */
s_pfnGetSystemTimes(&ft_sys_idle, /* System idle time */
&ft_sys_kernel, /* system kernel time */
&ft_sys_user); /* System user time */
CopyMemory(&ul_sys_idle , &ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_user , &ft_sys_user , sizeof(FILETIME)); // Could been optimized away...
usage =
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
(ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
(100)
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;
ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;
ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;
return usage;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
return TRUE;
#ifdef _MANAGED
#pragma managed(pop)
#endif
JNIEXPORT jstring JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
int n;
GetSystemTimesAddress();
jstring s=(jstring)cpuusage();
printf("CPU Usage from C++: %3d%%\r",s);
return s;
}actually in the above code below part does that all, in the below code the printf statement printing correctly
JNIEXPORT jstring JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
int n;
GetSystemTimesAddress();
jstring s=(jstring)cpuusage();
printf("CPU Usage from C++: %3d%%\r",s);
return s;
}and the NPE i get is
Exception in thread "main" java.lang.NullPointerException
at HelloWorld.print(Native Method)
at HelloWorld.main(HelloWorld.java:10)
CPU Usage from C++: 6%any solution?
Thanks
R
Edited by: LoveOpensource on Apr 28, 2008 12:38 AMSee the function you wrote:
JNIEXPORT jstring JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
int n;
GetSystemTimesAddress();
_jstring s=(jstring)cpuusage();_
printf("CPU Usage from C++: %3d%%\r",s);
return s;
}Here you try to cast from char to jstring, this is your problem, jstring Object should be created:
char str[20];
sprintf(str, "%3d", (int)cpuusage());
printf("CPU Usage from C++: %s%%\r",str);
jstring s=env->NewStringUTF(str);
return s; -
HashCode method return same value for different string?
Hello. I am finding hashCode method of string return same hashcode for many different string? It seem when string is long we get same value many times? What is solution? I am useing JDK 1.0.2. Thank you.
Hello. I am finding hashCode method of string return
same hashcode for many different string? There are about 4 billion possible hashcode values.
How many possible strings do you think there are?
Obviously many strings will have the same hashcode.
What is
solution?The solution is to not depend on hashcodes being unique. -
How to call a method if I have a name of a method in String format
Hi Guys,
I need an idea how to replace this large code. It has more then 50 else-if in a row
if ((readerElement.getFunction()).equals("clickButton")) {
testFrameWork.clickButton();
}else if ((readerElement.getFunction()).equals("clickButtonWait")) {
testFrameWork.clickButtonWait();
}else if ((readerElement.getFunction()).equals("clickCreateJob")) {
testFrameWork.clickCreateJob();
Of course switch can't be helpful in my case. I am using a Strings and switch will not make my code better.
I need something like:
testFrameWork.((readerElement.getFunction()).toString)() - This is of course bad code but I just want to give an idea what I am looking for
Can I call somehow method by adding a name of that method by String?!While reflections can be error prone, so is maintaining 50 if/else statements or 50 Command classes. You appear to have a good use case.
Method m = testFrameWork.getClass().getMethod(readerElement.getFunction());
m.invoke(testFrameWork); -
Week returned by Format Date/time String
Has anyone tested the Format Date/Time String function with the week formating codes?
I want to create a subfolder for each week and name the folder accordingly. For 17 December 2003 the week is 51 in the year 03 but I get week 50. For 29 December 2003 the week is 01 in the year 04 but I get week 52. For 01 January 2004 the week is 01 in the year 04 but I get week 00. For 29 December 2004 the week is 53 in the year 04 but I get week 52. For 01 January 2005 the week is 53 in the year 04 but I get week 00. There is no difference using %U or %W as code (this will be if 1 January will fall on Sunday or Monday which it does not in my examples).
I know normally a year has weeks 1 to 52 but in some years the last week may have week
53 as in 2004. Adding 1 to the week does not solve the problem. For 29 December 2003 it would give 53. And 53 maybe a correct week as in 2004. For 1 January 2005 it would give 1 but the week is the week in the year before.
All the week numbering I expect is correct for Germany but the function is not. Is the numbering from the function correct for your country?
Please reply where you are located and if the function will work right for you.
Waldemar
Waldemar
Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
Don't forget to give Kudos to good answers and/or questionsI have found two resources about date and time and their formats.
One is the ISO Standard 8601, the second is a german page. On this page along with other information all definitions used by Windows is listed.
According to this page the ISO Standard has been established in Europe and most industrial countries. In USA it is ANSI X3.30-1985(R1991) and NIST FIPS 4-1.
Since the ANSI definition you mentioned allows only Sunday (Jewish) or Monday (Christian) as first day of the week it ignores the Islamic world. For them the first day is Saturday. I could not gather information about Buddhistic or Hinduism
based countries.
For my application and the market aimed the ISO format is the one which will be choosen. Using %W and handling of week 0 should do it.
Waldemar
Waldemar
Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
Don't forget to give Kudos to good answers and/or questions -
Formatting the return value of: File(myFile).lastModified()
I'm checking file date and time stamps:
myDate = File(myFile).lastModified()Is there a way to format the return value?
myDate equals: 1205166439145I'd like to see something like:
03/10/2008 12:27 PMI'm using the following code to print the value:
System.out.println(myDate);Awesome! I really, really appreciate the help and the sample code!
Successful Output:
K:\COMMON\ITS\STEVEB\java\CompareFileDates>java CompareFileDates
execution continuing...
test1.steve (3/10/08 12:27 PM) is older than test2.steve (3/10/08 1:33 PM)Error free code:
import java.io.File;
import java.lang.Object;
import java.util.Date;
import java.text.Format;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class CompareFileDates {
public static void main(String[] args) {
String file1_stat = null;
String file2_stat = null;
String file1 = "test1.steve";
String file2 = "test2.steve";
long date1 = 0;
long date2 = 0;
String finalDate1 = null;
String finalDate2 = null;
boolean file1Exists = (new File(file1)).exists();
if (file1Exists) {
// File or directory exists
file1_stat = "does exist";
// Get the timestamp from file 1 and format it
date1 = (new File(file1)).lastModified();
Date newDate1 = new Date(date1);
DateFormat df = new SimpleDateFormat();
finalDate1 = df.format(newDate1);
//System.out.println(file1 + " date: " + finalDate1);
else {
// File or directory does not exist
file1_stat = "does not exist";
boolean file2Exists = (new File(file2)).exists();
if (file2Exists) {
// File or directory exists
file2_stat = "does exist";
// Get the timestamp from file 2 and format it
date2 = (new File(file2)).lastModified();
Date newDate2 = new Date(date2);
DateFormat df = new SimpleDateFormat();
finalDate2 = df.format(newDate2);
//System.out.println(file2 + " date: " + finalDate2);
else {
// File or directory does not exist
file2_stat = "does not exist";
if ((file1Exists == false) || (file2Exists == false)) {
System.out.println("aborting program...");
else {
System.out.println("execution continuing...");
String relation;
if (date1 == date2)
relation = "the same age as";
else if (date1 < date2)
relation = "older than";
else
relation = "newer than";
System.out.println(file1 + " (" + finalDate1 + ")" + " is " + relation + ' ' + file2 + " (" + finalDate2 + ")");
} -
Java.nio select() method return 0 in my client application
Hello,
I'm developing a simple chat application who echo messages
But my client application loop because the select() method return 0
This is my code
// SERVER
package test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class Server {
private int port = 5001;
public void work() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
serverSocketChannel.socket().bind(isa);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Listing on "+port);
while(selector.select()>0) {
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isAcceptable()) {
ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();
SocketChannel channel = keyChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ );
} else if (key.isReadable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel );
Help.write(m.toUpperCase(), keyChannel );
} catch (IOException e) {
e.printStackTrace();
public static void main(String[] args) {
Server s = new Server();
s.work();
// CLIENT
package test;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame {
private String host = "localhost";
private int port = 5001;
private SocketChannel socketChannel;
private Selector selector;
public void work() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(host, port);
socketChannel.connect(isa);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
while(true) {
selector.select();
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isConnectable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
if (keyChannel.isConnectionPending()) {
System.out.println("Connected "+keyChannel.finishConnect());
} else if (key.isReadable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel);
display(m);
} catch (IOException e) {
e.printStackTrace();
private void display(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
area.append(m+"\n");
textFieed.setText("");
private void sendMessage(final String m) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Help.write(m, socketChannel);
} catch (IOException e) {
e.printStackTrace();
t.start();
public Client() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(1);
textFieed.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()== KeyEvent.VK_ENTER) {
String m = textFieed.getText();
sendMessage(m);
area.setEditable(false);
getContentPane().add(textFieed, "North");
getContentPane().add(new JScrollPane(area));
setBounds(200, 200, 400, 300);
show();
private String messageToSend;
private JTextArea area = new JTextArea();
JTextField textFieed = new JTextField();
public static void main(String[] args) {
Client s = new Client();
s.work();
// HELPER CLASS
package test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class Help {
private static Charset charset = Charset.forName("us-ascii");
private static CharsetEncoder enc = charset.newEncoder();
private static CharsetDecoder dec = charset.newDecoder();
private static void log(String m) {
System.out.println(m);
public static String read(SocketChannel channel) throws IOException {
log("*** start READ");
int n;
ByteBuffer buffer = ByteBuffer.allocate(1024);
while((n = channel.read(buffer)) > 0) {
System.out.println(" adding "+n+" bytes");
log(" BUFFER REMPLI : "+buffer);
buffer.flip();
CharBuffer cb = dec.decode(buffer);
log(" CHARBUFFER : "+cb);
String m = cb.toString();
log(" MESSAGE : "+m);
log("*** end READ");
//buffer.clear();
return m;
public static void write(String m, SocketChannel channel) throws IOException {
log("xxx start WRITE");
CharBuffer cb = CharBuffer.wrap(m);
log(" CHARBUFFER : "+cb);
ByteBuffer buffer = enc.encode(cb);
log(" BUFFER ALLOUE REMPLI : "+buffer);
int n;
while(buffer.hasRemaining()) {
n = channel.write(buffer);
System.out.println(" REMAINING : "+buffer.hasRemaining());
log("xxx end WRITE");Here's the fix for that old problem. Change the work method to do the following
- don't register interest in things that can't happen
- when you connect register based on whether the connection is complete or pending.
- add the OP_READ interest once the connection is complete.
This doesn't fix all the other problems this code will have,
eg.
- what happens if a write is incomplete?
- why does my code loop if I add OP_WRITE interest?
- why does my interestOps or register method block?
For code that answers all those questions see my obese post Taming the NIO Circus
Here's the fixed up Client code
// CLIENT
package test
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame {
private String host = "localhost";
private int port = 5001;
private SocketChannel socketChannel;
private Selector selector;
public void work() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(host, port);
socketChannel.connect(isa);
selector = Selector.open();
int interest = 0;
if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
socketChannel.register(selector, interest);
while(true)
int nn = selector.select();
System.out.println("nn="+nn);
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();)
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isConnectable())
SocketChannel keyChannel = (SocketChannel) key.channel();
System.out.println("Connected "+keyChannel.finishConnect());
key.interestOps(SelectionKey.OP_READ);
if (key.isReadable())
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel);
display(m);
} catch (IOException e) {
e.printStackTrace();
private void display(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
area.append(m+"\n");
textFieed.setText("");
private void sendMessage(final String m) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Help.write(m, socketChannel);
} catch (IOException e) {
e.printStackTrace();
t.start();
public Client() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(1);
textFieed.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()== KeyEvent.VK_ENTER) {
String m = textFieed.getText();
sendMessage(m);
area.setEditable(false);
getContentPane().add(textFieed, "North");
getContentPane().add(new JScrollPane(area));
setBounds(200, 200, 400, 300);
show();
private String messageToSend;
private JTextArea area = new JTextArea();
JTextField textFieed = new JTextField();
public static void main(String[] args) {
Client s = new Client();
s.work(); -
Returning String data through argument
I need to write a method to call the following method:
int myFunc(char *buf, int code);
Where I need the return value integer and I also want to get back the char * as a string.
I am thinking the most straightforward thing to do would be:
public native int myFunc(StringBuffer sb, int code);
and then in my native code create the return string and use the MethodID functions to call the StringBuffers append() method.
I considered making two functions - one to get the string and one to check for an error, but figured that could cause threading implications in the future.
I assume this is a common issue, is there a recommended solution?
Thanks,
mikeSorry I didn't reply earlier- never really came back to this thread - the solution I suggested in my first message worked great for me.
Here's what it looks like (the relevant bits at least):
* Class: com_nmss_ms_log_hsLogger
* Method: lgGetText
* Signature: (Ljava/lang/StringBuffer;Ljava/lang/String;I)I
JNIEXPORT jint JNICALL Java_com_nmss_ms_log_hsLogger_lgGetText
(JNIEnv *env, jobject obj, jobject stringBuf, jstring id, jint msgId, jchar ss_id)
char buff[501];
int result, i;
jstring retString;
jclass cls = (*env)->GetObjectClass(env, stringBuf);
jmethodID mid = (*env)->GetMethodID(env, cls, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
result = logGetText(log_handle, msgId, buff, 500);
retString = (*env)->NewStringUTF(env, buff);
(*env)->CallObjectMethod(env, stringBuf, mid, retString);
return result;
} -
In report layout, can format a long string display as Column mode?
Hi,
Just want to check in report builder any way can format a long string into a column mode?
Example: I have a field to hold 8000 character, and would like to print
30 character in each line, when reach 50 line, then print in column i/o to print next page?
Any idea ? Thanks a lot if you can share your experience with me.
best Regards,
Klnghauhi let say your field name is x
then if your want it word wrap then it's simple just get one field and make it's vertical
elasticity variable. and asign the field to it..
but if you want your field to be displayed as
first colunm and then beside continuation of that column but in 2nd one...
then create 2 formula columns make your field legth been distributed half in each.
so cf_1 is:
decalre
t varchar2(1510);
begin
if length(:x) > 1500
t := substr(x, 1, 1500); -- as 30 x 50 = 1500
else
t := :x;
end if;
return t;
so cf_2 is:
decalre
t varchar2(1510);
begin
if length(:x) > 1500
t := substr(x, 1500, length(:x)-1500); -- as 30 x 50 = 1500
else
t := '';
end if;
return t;
and then in design view
field1 field2
for field1 source is cf_1 and
for field2 source is cf_2
that's all
Enjoy Oracle... -
Returning strings of the same name in a text file from an array
Hi,
Another quick question. I have a text file with lines consisting of one integer, and four strings. Currently, I am able to search through this file and find any of the variables listed within. However, if any of the variables are listed more than once, and I search for that particular varable name, it only prints out the first line containing that particular variable name.
Basically, how do I modify the following code so that the search method returns all the instances of a particular variable name in the text file?
My current code is as follows,
1. Search method,
public Title lookUpDirector(String requiredDetails) {
boolean found = false;
int next = 0;
while (!found && (next<TitleCount))
if ( TitleArray[next].getDirector().equals(requiredDetails))
found = true;
else next++;
if (found) return TitleArray[next];
else return null;
}2. Test main class
import simplejava.*;
public class SearchTitleDirector
public static void main(String[] args) {
String titleDetails;
SimpleReader keyboard = new SimpleReader();
SimpleWriter screen = new SimpleWriter();
SimpleReader inFile = new SimpleReader("title_test.txt");
TitleList title = new TitleList(inFile);
TitleList[] sortedArray = new TitleList[]{title};
titleDetails=keyboard.readLine("Director?");
Title search = title.lookUpDirector(titleDetails);
if (search == null)
screen.println("Not found");
else screen.println(search);
}Any help or advice appreciated!Thanks for the reply and advice.
I have tried implementing the lookUpDirector method as follows,
public TitleList lookUpDirector(String requiredDetails) {
boolean found = false;
int next = 0;
TitleList list = new TitleList();
while (!found && next<titleCount) {
if ( titleArray[next].getDirector().equals(requiredDetails)) {
list.add(titleArray[next]);
next++;
if (found) return list;
else return null;
}When I use this method with the previous test main class, it compiles and runs, but after the user inputs the name of the director to search for, the input window freezes indefinitely and no result is achieved. The output pane in NetBeans is as follows,
init:
deps-jar:
compile-single:
run-single:
Director?The only way to stop the process is to terminate it in the Runtime section of NetBeans.
I have no idea why this is happening. Any advice?
Maybe you are looking for
-
How to upgrade ipod touch 4th generation ios
I have a 4th gen. iPod Touch (bought for Christmas last year) and just got my kids Touches for Christmas this year. Under Settings/General, the kids' Touches have an option for Software Update, but on last year's Touch, there is no such option. It
-
I also noticed when I tried using my Flashlight app I get a message that says another app is using your LED. Is this all inter-related? How can I find out what other app is using my LED?
-
Swing doesn't refresh/repaint properly
Hi, I'm trying to display a very simple dialog that just about says "Please wait" while I do i/o extensive processing, and can't for the life of me succeed. I tried many things, including Threads, SwingWorker, to no avail. Something seems fishy in th
-
How In Ecc 6.0 Transport Managment system works..
Hi gurus, Any document and some tips about, what is the functionality Transport Management does. TMS functionality Starts once after shipping when we do physical delivery. Laxman
-
I have a Netgear CG3100D. When I try to set up MAC filtering (by loging into the Admin console), the list of trusted devices never seems to be accurate (i.e. things are missing off the list) and does not pull in the actual device names. Can anyone h