Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, 22 July 2009

16-bit binary data interpreting difference between Java and Matlab

The 16-bit data will be interpreted as different values in Java and Matlab. WHY??

Here are some experiments: save number 15 to 8-bit and 16-bit binary files, and another 259 in 16-bit binary files (refer to : this post).
======================

In Matlab (fread(fid1, 'uint8');): 15

16 bit bin file containing 15:
In WinHex: 0F 00
In java (DataInputStream.readShort();): [3840, 0]
=> 3840/256=15;
=> so, it's a kind of [15 00]
In Matlab (fread(fid1, 'uint16');): 15

16 bit bin file containing 259:
In WinHex: 03 01
In java (DataInputStream.readShort();): [769, 0] //Note, for every byte, java can

contain a value larger than 256, while other programming language will increment.
=> 769%256 = 1; 769/256=3.0039;
=> so, it's a kind of [03 01]
In Matlab (fread(fid1, 'uint16');): 259

Therefore:
========================
Therefore, a integer value in the range of 16-bit, for example 41837. In Matlab,

it will be intepreted as 41837, mod(41837,256)=109, 41837/256=163.4. So 41837 can

be displayed as [163 109] = 163*256+109; while java intepret [163 109] as

163+109*256 = 28067;


Conclusion:
========================
This seems wrong inside Java, but Java know how to process such value and export

it correctly to another bin file, which one can be understood by Matlab, WinHex or

other programming languages or editor.

Tuesday, 21 July 2009

Java/Matlab read and write 16-bit data file

  • Read 16 bit binary file:
    File file = new File("FILENAME.bin");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream( bis );

    short[] myarray = new short[256000];
    int cnt;
    for (cnt = 0; cnt < 256000; cnt++) {

    myarray[cnt] = dis.readShort();

    }
    fis.close();

    Alternatively:
    RandomAccessFile dis = new RandomAccessFile(new File("FILENAME.bin"), "r");

    Note:
    1) bufferedInputStream can be ignored, but it will improve the performance 90% for large file operation.
    2) RandomAccessFile works like a 'pointer', similar to fread in Matlab, offset or skip can be assign when data retrieving while not really load all the file. This class has both read and write methods, it is a convenience class, like filereader and filewriter, while the former method is kinda low level methods.

  • Write 16 bit binary file:
    FileOutputStream fos = new FileOutputStream(new File("OUTPUT.bin"));
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    DataOutputStream dos = new DataOutputStream(bos);

    for (cnt = 0; cnt < 256000; cnt++) {

    myarray[cnt] = dis.readShort();

    }

    bos.flush();

    fos.close();

    Alternatively:
    RandomAccessFile dos = new RandomAccessFile(new File("OUTPUT.bin"), "rw");
    Note: The following step is essential!!!! Otherwise, there will be some data lost.
    bos.flush();
  • Matlab:

    fid1 = fopen('filename.bin', 'r');
    A = fread(fid1, 100, 'uint16=>float32');
    fclose(fid1);

    fid2 = fopen('output.bin', 'w');
    fwrite(fid2, A, 'uint16');
    fclose(fid2);

Sunday, 19 July 2009

BUG, HOWTO: how java read 8-bit and 16-bit

you have to use twice as much memory, but there really is no other solution:
=======================

use a short to hold an unsigned byte, use a long to hold an unsigned int. (And use a char to hold an unsigned short.)

This example create a 16-bit file, which only contain a value, 15 in 16-bit (000f), This file can be viewed by Gedit. From Matlab, it can retrieve and display correctly as 15, but in Java, using DataInputStream.readShort(), it's 3840, which equals to 15*256.



Example 1: Using Matlab to generate a 16-bit data file.
================
clear;clc;%% create binA=15;fid = fopen('output.bin', 'w'); fwrite(fid, A, 'uint16');fclose(fid);%% read binfid1 = fopen('output.bin', 'r'); B = fread(fid1, 1, 'uint16')fclose(fid1);

Example 2: Using Java to retrive the 16-bit data from the bin file.
===========
import java.io.*;public class convbin { public static void main(String args[]) throws IOException { File file = new File("onev.bin"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream( bis );// RandomAccessFile dis = new RandomAccessFile(new File("fotech1.bin"), "r"); short[] myarray = new short[256000]; int cnt; for (cnt = 0; cnt < 1; cnt++) { myarray[cnt] = dis.readShort(); } fis.close(); System.out.println("Done."); FileOutputStream fos = new FileOutputStream(new File("o22.bin")); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos);// RandomAccessFile dos = new RandomAccessFile(new File("o22.bin"), "rw"); for (cnt = 0; cnt < 1; cnt++) { dos.writeShort(myarray[cnt]); } System.out.println("Finish."); bos.flush(); fos.close(); }}

More details, except the example: http://www.darksleep.com/player/JavaAndUnsignedTypes.html

Saturday, 7 March 2009

Profiler for Eclipse Java Development Tool

TPTP, as java profiler for eclipse, so far version 4.5.2, still relies on very old gcc, libstdc++2.10-glibc2.2.
To solve this, compat-libstdc++ should be installed for the compatibility.

To get more statistics result, besides TPTP project, try to install more modules, such as trace, logging tools etc.

Note:
=============
1) For Ubuntu, the above gcc binary is not available in the repository any more. But google it will find some downloads: http://packages.ubuntu.com/gutsy/i386/libstdc++2.10-glibc2.2/download

2) For Ubuntu, Tptp also using java 1.5 to capture the jvm information. If got error message like : "ERROR: JVMPI, an experimental interface, is no longer supported.". The fix is:
Go to eclipse/plugins/org.eclipse.tptp.platform.ac.linux_ia32_4.4.1.v200808290100/agent_controller/bin, and edit the files ACStart.sh, ACStop.sh. In first line, when it says #!/bin/sh, it should say #!/bin/bash.
Otherwise, just use 'netbeans' to profile your java programs :)

Thursday, 5 February 2009

WHATIS: Jave Bean

今天看到perry写了一个很强大的jsp page,通过java bean调用linux server上的matlab程序并执行一些在页面上输入的matlab代码,运行结果可以直接显示在jsp page上。

java bean 是一个java模型组件,他为使用java类提供了一种标准的格式,在用户程序和可视化管理工具中可以自动获得这种具有标准格式的类的信息,并能够创建和管理这些类。
java bean 可以使应用程序更加面向对象,可以把数据封装起来,把应用的业务逻辑和显示逻辑分离开,降低了开发的复杂程度和维护成本!
回答者: shutgun - 秀才 二级 3-29 09:26
Bean
Bean是Enterprise Java Bean的缩写
就是组件的意思。它是为了实现某一个功能而设计的。也可以把一些常量,方法封装进去。实现很好的结构化效果,体现面向对象方面的优势。它的功能简单点说就相当于一个零件。

在JSP中使用 Java Bean的一个例子:
test.jsp的代码如下:

<html>

<head>

<title>JSP中使用 Java Bean的测试</title>

</head>

<body>

<jsp:useBean id="test" class="SimleBean" />

<jsp:setProperty name="test" property="message" value="Hello JSP"/>

<p>消息:

<jsp:getProperty name="test" property="message" />

</body>

</html>



解释:

:表示定义一个java bean的实例,实例的名称是test,类的名称是SimleBean。
:表示设置实例test的属性message,其值是"Hello JSP"。
:表示在页面中输出实例test的属性message的值。

· test.jsp文件中用到的java bean 的代码SimpleBean.java如下:

public class SimpleBean
{
private String message;

public String getMessage()
{
return message;
}

public void setMessage(String message)
{
this.message = message;
}
}



1、

javaBean是特殊类型的java类,它与普通java类相比主要区别是包含了两种特殊的方法:set…(设置属性的方法)、get…(取属性值的方法)。
动作用来查找或实例化一个jsp页面使用的JavaBeans组件。
在程序中可把逻辑控制、数据库操作放在javabeans组件中,然后在jsp文件中调用它,这样可增加程序的清晰度及程序的可重用性。

· 语法如下:

scope="page | request | session | application"
class="package.claaa"
type="package.claaa"
other elements
/>

· 属性:

1) id="beanInstanceName"
用来绑定Bean实例的变量。
2) class|type="package.claaa"
表明该bean具体是对哪个类的实例化。
3) scope="page | request | session | application"
表示该bean的有效范围。
Page:实例的有效范围是当前页面。
Request:实例的有效范围是一个单独客户请求的生命周期内。
Session:实例的有效范围是整个用户会话的生命周期内。
Application:实例的有效范围是应用的生命周期内。

2、

该动作的含义是使用bean中相应的set()方法设置一个或多个属性的值,值的来源是通过value属性明确给出,或者利用request对象中相应的参数。
假设某个bean有一个string类型的可被JSP文件使用的属性myProperty,则它必须有一个public方法setMyProperty(string value),动作使用的就是该方法。

· 语法如下:

property="*" | property ="propertyName"
value="具体的值"
/>

· 属性:

1) name="beanInstanceName"
这个属性是必须的,用来表明对哪个bean实例执行下面的动作,这个值和动作中定义的id必须对应起来,包括大小写都必须一致。
2) property="*" | property ="propertyName"
这个属性是必须的,用来表示要设置哪个属性。如果property的值是"*",表示用户在可见的JSP页面中输入的全部值,存储在匹配的bean属性中。匹配的方法是:bean的属性名称必须与输入框的名字相同。
3) value="具体的值"
它用来指定bean的属性的值。

3、

这个动作提取指定bean属性的值,转换成字符串,然后输出。该动作实际是调用了bean的get()方法。
按上文提到的某个bean有一个string类型的可被JSP文件使用的属性myProperty,它必须有一个返回类型为string的public方法getMyProperty()。使用的就是这个方法。

语法如下:



· 属性:

1) name="beanInstanceName"
这个属性是必须的,用来表明对哪个bean实例执行下面的动作,这个值和动作中定义的id必须对应起来,包括大小写都必须一致。
2) property="*" | property ="propertyName"
这个属性是必须的,用来表示要获取哪个属性。

Monday, 26 January 2009

Jython and Matlab do jobs for java

Java codes:
======================
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyExample
implements ActionListener {

public void actionPerformed(ActionEvent e) {
System.out.println("Ouch!");
}

public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(300,300);
JButton button = new JButton("Push Me!");
ActionListener listener = new MyExample();
button.addActionListener(listener);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}


Jython:
======================
import javax.swing as swing

def printMessage(event):
print "Ouch!"

frame=swing.JFrame("my frame")
frame.setSize(300,300)
button=swing.JButton("Push Me!")
button.actionPerformed=printMessage
frame.getContentPane().add(button)
frame.setVisible(True) #frame.visible=1


Matlab:
=======================
import javax.*;

frame = swing.JFrame('my frame');
frame.setSize(300,300);
button = swing.JButton('Push Me!');

set(button,'ActionPerformedCallback',@printMessage);

frame.getContentPane.add(button);
frame.setVisible(true);

%code for sub function:
function printMessage(handle,event)
disp('ouch');
end

Saturday, 10 January 2009

HOWTO: make “the java plugin” work on Firefox in Fedora 10 / Linux Distro?

1) locate the file named libjavaplugin_oji.so on your box by issuing the following command at the prompt:


[dkd903@dkd903-laptop ~]$ locate libjavaplugin_oji.so


you`ll find that the file libjavaplugin_oji.so is available in the /usr/java/jre1.6.0_07/plugin/i386/ directory.


2) Then what you need to do is just link the .so file symbolically to the mozilla plugins folder, and you are done:


[dkd903@dkd903-laptop ~]$ sudo   ln  -s  
/usr/java/jre1.6.0_07/plugin/i386/ns7/libjavaplugin_oji.so  
/usr/lib/mozilla/plugins/libjavaplugin_oji.so

Thursday, 27 November 2008

HOWTO: jython(java) calling c program in console

import java.lang

proc=java.lang.Runtime.getRuntime().exec("c:\\app.exe") // this app.exe is compiled from c
br=java.io.BufferedReader(java.io.InputStreamReader(proc.getInputStream()))
print br.readLine()
java.lang.System.out.println("last line")

=========================
Why not using os.popen() from python, is because there is a bug about calling popen. :)

Saturday, 12 July 2008

Java/Jython to read file

All the programs is quite preliminary and in Jython environment.

1. BufferedReader + FileReader
====================
import java.io as ji
fr=ji.FileReader('a.txt')
br=ji.BufferedReader(fr)
text=br.readLine()

2. FileInputStream + BufferedInputStream + DataInputStream
====================
import java.io as ji
fis=ji.FileInputStream('a.txt')
bis=ji.BufferedInputStream(fis)
dis=ji.DataInputStream(bis)
text=dis.readLine()

3. FileInputStream + BufferedInputStream + InputStreamReader + BufferedReader
====================
import java.io as ji
fis=ji.FileInputStream('a.txt')
bis=ji.BufferedInputStream(fis)
isr=ji.InputStreamReader(bis)
br=ji.BufferedReader(isr)
text=br.readLine()

Thursday, 27 March 2008

Two examples of matlab implement java

Example 1: print a line
===================
import java.lang.System;
System.out.println('zhengxin');

% in Java environment, java.lang.* is automatically imported, so no need to import it when programming with java. But in Matlab, this package/classes must be imported manually.


Example 2: show a dialog
===================
import java.awt.*;
import javax.swing.*;

title = 'Frame Title';
frame = JFrame(title);
comp = JTextArea();
frame.getContentPane.add(comp, BorderLayout.CENTER);
width = 300;
height = 300;
frame.setSize(width, height);
frame.show();

Sunday, 9 March 2008

develop, deploy and run java servlet

///////////1. Java Class ///////////////////////////
If you are not using Java EE SDK, you must download Java Servlet Api:servlet-2_5-api.jar, than put it in the classpath.

// HW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HW extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<-html->");
out.println("<-head->");
out.println("<-title->Hello World!<-/title->");
out.println("<-/head->");
out.println("<-body->");
out.println("<-h1->Hello World!<-/h1->");
out.println("<-h1->By Cross<-/h1->");
out.println("<-/body->");
out.println("<-/html->");
}
}


/////////// Deploy it ///////////////////////////////
Put the class in \Tomcat\webapps\ROOT\WEB-INF\classes
Edit web.xml by append following 'xml' element.

// web.xml in \Tomcat\webapps\ROOT\WEB-INF
<-servlet->
<-servlet-name->myHelloWorld<-/servlet-name->
<-servlet-class->HW<-/servlet-class->
<-/servlet->
<-servlet-mapping->
<-servlet-name->myHelloWorld<-/servlet-name->
<-url-pattern->/myHello<-/url-pattern->
<-/servlet-mapping->

////////// Run it ///////////////////////////////////
Start Tomcat, then run it like this:
http://localhost/myHello

P.S.: use '<' and '>' to replace '<-' and '->' to escape Blogspot parsing html tag.
How getParameters from request, see here:
http://java.sun.com/developer/technicalArticles/RMI/rmi/
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Servlets/Q_22996074.html?eeSearch=true

Wednesday, 5 March 2008

java applet <> javascript

1. javascript call java applet: http://www.rgagnon.com/javadetails/java-0170.html

* make the variable you want to call public in the applet.
* in javascript just: document.myapplet.myfunction(some parametres);

2.1 java applet call variable or function defined in javascript:

* You can try an easy method, by calling a specially crafted URL using the showDocument() method, like this :
getAppletContext().showDocument(new URL("javascript:alert(Hello World);));
This doesn't work anymore using Internet Explorer as of a certain IE update from Microsoft dated some time ago this year, so it is easily broken.

* You can use the LiveConnect objects that are implemented in IE on Windows, Mozilla/Firefox on anything, Safari on Mac, etc.. it works almost everywhere.
For this you have to declare that your applet MAYSCRIPT, by adding a special parameter in the OBJECT/EMBED tag in your web page. (google for it if you need examples).
Then you have to add the "jaws.jar" (or "plugin.jar" if there's no jaws.jar) from the lib of the JRE to compile your Applet.
This jar should include the LiveConnext classes, and netscape.javascript.JSObject is the one you need.
Then You can then do something like this to achieve the same as solution one above :
JSObject browserWindow = JSObject.getWindow(this); //here 'this' is the JApplet
browserWindow.eval(buffer.toString());
Or you can navigate the DOM javascript tree of the WebPage using the methods of JSObject. (google for it if you need more info).

2.2 java applet call variable defined in html:
Just use the parametre of applet, for example:


Tuesday, 4 March 2008

simplest way to config java security policy

In my case, on xp, these security policy files are stored here:
C:\Program Files\Java\jre1.6.0_04\lib\security

So, when applet need to access local or remote file, the "java.policy" should be modified.

Eclipse will generate a very dangerous java.policy.applet by default for testing, you can copy the setting permission line in to java.policy, in this case, your applet can reading files. But it's dangerous.

My way is to put such code in the java.policy. where the path is the place where my applet class file exists.

grant codeBase "file:///D:/My%20Documents/workspace/2008.3.applet/bin/" {
permission java.security.AllPermission;
};

Sunday, 2 March 2008

java copy file

[Old technique (pre JDK1.4)]

import java.io.*;

public class FileUtils{
public static void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
throw e;
}
finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
}

public static void main(String args[]) throws Exception{
FileUtils.copyFile(new File(args[0]),new File(args[1]));
}
}

[JDK1.4 using the java.nio package (faster)]

import java.io.*;
import java.nio.channels.*;

public class FileUtils{
public static void copyFile(File in, File out)
throws IOException
{
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}

public static void main(String args[]) throws IOException{
FileUtils.copyFile(new File(args[0]),new File(args[1]));
}
}
NOTE:
In win2000 , the transferTo() does not transfer files > than 2^31-1 bytes. it throws an exception of "java.io.IOException: The parameter is incorrect"
In solaris8 , Bytes transfered to Target channel are 2^31-1 even if the source channel file is greater than 2^31-1
In LinuxRH7.1 , it gives an error of java.io.IOException: Input/output error


more details are on:http://www.rgagnon.com/javadetails/java-0064.html

Friday, 29 February 2008

java download file program

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class downloadit {

/**
* @param args
*/
public static void main(String[] args) {
// // TODO Auto-generated method stub
// URL url = new URL("http://pagead2.googlesyndication.com/pagead/show_ads.js");
// BufferedReader br = new BufferedReader(new InputStream(url));
//// new BufferReader (new InputStremReader());

OutputStream out;
URLConnection conn;
InputStream in;
try {
String address = "http://pagead2.googlesyndication.com/pagead/show_ads.js";
String localFileName = "downloaed";
URL url = new URL(address);
out = new BufferedOutputStream(
new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
} catch (Exception exception) {
exception.printStackTrace();
}

}

}

Thursday, 28 February 2008

java文件操作

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class FileOperate {
private String message;
public FileOperate() {
}

/**
* 读取文本文件内容
* @param filePathAndName 带有完整绝对路径的文件名
* @param encoding 文本文件打开的编码方式
* @return 返回文本文件的内容
*/

public String readTxt(String filePathAndName,String encoding) throws IOException{
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try{
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if(encoding.equals("")){
isr = new InputStreamReader(fs);
}else{
isr = new InputStreamReader(fs,encoding);
}
BufferedReader br = new BufferedReader(isr);
try{
String data = "";
while((data = br.readLine())!=null){
str.append(data+" ");
}
}catch(Exception e){
str.append(e.toString());
}
st = str.toString();
}catch(IOException es){
st = "";
}
return st;
}

/**
* 新建目录
* @param folderPath 目录
* @return 返回目录创建后的路径
*/

public String createFolder(String folderPath) {
String txt = folderPath;
try {
java.io.File myFilePath = new java.io.File(txt);
txt = folderPath;
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
}
catch (Exception e) {
message = "创建目录操作出错";
}
return txt;
}

/**
* 多级目录创建
* @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf
* @param paths 无限级目录参数,各级目录以单数线区分 例如 a|b|c
* @return 返回创建文件后的路径 例如 c:myfac
*/

public String createFolders(String folderPath, String paths){
String txts = folderPath;
try{
String txt;
txts = folderPath;
StringTokenizer st = new StringTokenizer(paths,"|");
for(int i=0; st.hasMoreTokens(); i++){
txt = st.nextToken().trim();
if(txts.lastIndexOf("/")!=-1){
txts = createFolder(txts+txt);
}else{
txts = createFolder(txts+txt+"/");
}
}
}catch(Exception e){
message = "创建目录操作出错!";
}
return txts;
}


/**
* 新建文件
* @param filePathAndName 文本文件完整绝对路径及文件名
* @param fileContent 文本文件内容
* @return
*/

public void createFile(String filePathAndName, String fileContent) {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
resultFile.close();
}
catch (Exception e) {
message = "创建文件操作出错";
}
}


/**
* 有编码方式的文件创建
* @param filePathAndName 文本文件完整绝对路径及文件名
* @param fileContent 文本文件内容
* @param encoding 编码方式 例如 GBK 或者 UTF-8
* @return
*/

public void createFile(String filePathAndName, String fileContent, String encoding) {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
PrintWriter myFile = new PrintWriter(myFilePath,encoding);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
}
catch (Exception e) {
message = "创建文件操作出错";
}
}


/**
* 删除文件
* @param filePathAndName 文本文件完整绝对路径及文件名
* @return Boolean 成功删除返回true遭遇异常返回false
*/

public boolean delFile(String filePathAndName) {
boolean bea = false;
try {
String filePath = filePathAndName;
File myDelFile = new File(filePath);
if(myDelFile.exists()){
myDelFile.delete();
bea = true;
}else{
bea = false;
message = (filePathAndName+"
删除文件操作出错");
}
}
catch (Exception e) {
message = e.toString();
}
return bea;
}


/**
* 删除文件夹
* @param folderPath 文件夹完整绝对路径
* @return
*/

public void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
}
catch (Exception e) {
message = ("删除文件夹操作出错");
}
}


/**
* 删除指定文件夹下所有文件
* @param path 文件夹完整绝对路径
* @return
* @return
*/

public boolean delAllFile(String path) {
boolean bea = false;
File file = new File(path);
if (!file.exists()) {
return bea;
}
if (!file.isDirectory()) {
return bea;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
}else{
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+ tempList[i]);//再删除空文件夹
bea = true;
}
}
return bea;
}


/**
* 复制单个文件
* @param oldPathFile 准备复制的文件源
* @param newPathFile 拷贝到新绝对路径带文件名
* @return
*/

public void copyFile(String oldPathFile, String newPathFile) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
FileOutputStream fs = new FileOutputStream(newPathFile);
byte[] buffer = new byte[1444];
while((byteread = inStream.read(buffer)) != -1){
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}catch (Exception e) {
message = ("复制单个文件操作出错");
}
}

/**
* 复制整个文件夹的内容
* @param oldPath 准备拷贝的目录
* @param newPath 指定绝对路径的新目录
* @return
*/

public void copyFolder(String oldPath, String newPath) {
try {
new File(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}catch (Exception e) {
message = "复制整个文件夹内容操作出错";
}
}


/**
* 移动文件
* @param oldPath
* @param newPath
* @return
*/

public void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);
}

/**
* 移动目录
* @param oldPath
* @param newPath
* @return
*/

public void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
public String getMessage(){
return this.message;
}
}

Monday, 25 February 2008

java dialog: simplest prompt

String temp = javax.swing.JOptionPane.showInputDialog("Please enter your name: ");

System.out.println(temp);

Thursday, 21 February 2008

two ways to synchronized in Java

The following two examples are the classic consumer/producer example of multithread programming. Here I used two ways of invoking synchronized to do such a job.

  1. synchronized method:

    import java.util.*;

    public class Que {

    /**
    * @param args
    */
    public static void main(String[] args) {

    mapQ q = new mapQ();

    new genQ(q);
    new conQ(q);
    }
    }

    ////////////////// the commodity Queue /////////////////
    class mapQ {

    String s;
    LinkedList que = new LinkedList();

    synchronized void put(String s) {

    if (que.size()>10)
    try {
    wait();
    }
    catch(InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    que.addLast(s);
    System.out.println("Put: " + s);
    notify();
    }

    synchronized String get() {

    if (que.isEmpty())
    try {
    wait();
    }
    catch (InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    String temps = (String) que.removeFirst();
    // System.out.println(que);
    System.out.println("Got: " + temps);
    notify();

    return temps;
    }
    }

    //////////////// producer /////////////////////
    class genQ implements Runnable {
    mapQ q;

    genQ(mapQ q) {
    this.q=q;
    new Thread(this, "Producer").start();
    }
    public void run() {
    int i=0;

    while(true) {
    int tempi = i++;
    q.put(Integer.toString(tempi));
    }
    }
    }

    /////////////// consumer ///////////////////////
    class conQ implements Runnable {
    mapQ q;

    conQ(mapQ q) {
    this.q=q;
    new Thread(this, "Consumer").start();
    }

    public void run() {
    while(true) {
    q.get();
    }
    }
    }





  2. synchronized block:

    import java.util.*;

    public class Que {

    /**
    * @param args
    */
    public static void main(String[] args) {

    mapQ q = new mapQ();

    new genQ(q);
    new conQ(q);
    }
    }

    ////////////////// the commodity Queue /////////////////
    class mapQ {

    String s;
    LinkedList que = new LinkedList();

    void put(String s) {
    synchronized(que){
    if (que.size()>10)
    try {
    que.wait();
    }
    catch(InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    System.out.println(que);
    que.addLast(s);
    // System.out.println("Put: " + s);
    que.notify();
    }
    }

    String get() {
    synchronized(que){
    if (que.isEmpty())
    try {
    que.wait();
    }
    catch (InterruptedException e) {
    System.out.println("InterruptedException caught");
    }
    String temps = (String) que.removeFirst();
    // System.out.println("Got: " + temps);
    que.notify();

    return temps;
    }
    }
    }

    //////////////// producer /////////////////////
    class genQ implements Runnable {
    mapQ q;

    genQ(mapQ q) {
    this.q=q;
    new Thread(this, "Producer").start();
    }
    public void run() {
    int i=0;

    while(true) {
    int tempi = i++;
    q.put(Integer.toString(tempi));
    }
    }
    }

    /////////////// consumer ///////////////////////
    class conQ implements Runnable {
    mapQ q;

    conQ(mapQ q) {
    this.q=q;
    new Thread(this, "Consumer").start();
    }

    public void run() {
    while(true) {
    q.get();
    }
    }
    }

###########################################################

P.S.:
The second choice is much clearer and flexible, but you should be careful how to call the wait() and notify(), which should be called by the synchronized object.

java synchronized example

具体到应用比较复杂,举两个例子:
1:

public class Test1 implements Runnable {

public void run() {
synchronized(this) {
try {
System.out.println(System.currentTimeMillis());
Thread.sleep(2000);
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
Test1 test=new Test1();
for(int i=0;i<10;i++) {
new Thread(test).start();
}
}
}


2:
public class Test1 implements Runnable {

public void run() {
synchronized(this) {
try {
System.out.println(System.currentTimeMillis());
Thread.sleep(2000);
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
for(int i=0;i<10;i++) {
new Thread(new Test1()).start();
}
}
}

两个例子中,都有一段synchronized的代码。
在1中,main方法中创建的10个线程 不能同时进入到那段代码执行,因为这10个线程需要让
同一个object授权
而
在2中,main方法中创建的10个线程 可以同时进入到那段代码执行,因为10个线程是让不同
的object授权的,均授权成功,同时进入到那段代码执行.

java中synchronized用法

synchronized的一个简单例子


public class TextThread

{


/**

* @param args

*/

public static void main(String[] args)

{

// TODO 自动生成方法存根

TxtThread tt = new TxtThread();

new Thread(tt).start();

new Thread(tt).start();

new Thread(tt).start();

new Thread(tt).start();

}


}

class TxtThread implements Runnable

{

int num = 100;

String str = new String();

public void run()

{

while (true)

{

synchronized(str)

{

if (num&gt;0)

{

try

{

Thread.sleep(10);

}

catch(Exception e)

{

e.getMessage();

}

System.out.println(Thread.currentThread().getName()+ "this is "+ num--);

}

}

}

}

}


上面的例子中为了制造一个时间差,也就是出错的机会,使用了Thread.sleep(10)


Java对多线程的支持与同步机制深受大家的喜爱,似乎看起来使用了synchronized关键字就可以轻松地解决多线程共享数据同步问题。到底如何?――还得对synchronized关键字的作用进行深入了解才可定论。


总的说来,synchronized关键字可以作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块。如果再细的分类,
synchronized可作用于instance变量、object reference(对象引用)、static函数和class
literals(类名称字面常量)身上。


在进一步阐述之前,我们需要明确几点:


A.无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问。


B.每个对象只有一个锁(lock)与之相关联。


C.实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。


接着来讨论synchronized用到不同地方对代码产生的影响:


假设P1、P2是同一个类的不同对象,这个类中定义了以下几种情况的同步块或同步方法,P1、P2就都可以调用它们。


1. 把synchronized当作函数修饰符时,示例代码如下:


Public synchronized void methodAAA()


{


//….


}


这也就是同步方法,那这时synchronized锁定的是哪个对象呢?它锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程
中执行这个同步方法时,它们之间会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一对象P2却可以任意调用这个被加了
synchronized关键字的方法。


上边的示例代码等同于如下代码:


public void methodAAA()


{


synchronized (this) // (1)


{


//…..


}


}


(1)处的this指的是什么呢?它指的就是调用这个方法的对象,如P1。可见同步方法实质是将synchronized作用于object
reference。――那个拿到了P1对象锁的线程,才可以调用P1的同步方法,而对P2而言,P1这个锁与它毫不相干,程序也可能在这种情形下摆脱同
步机制的控制,造成数据混乱:(


2.同步块,示例代码如下:


public void method3(SomeObject so)


{


synchronized(so)


{


//…..


}


}


这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:


class Foo implements Runnable


{


private byte[] lock = new byte[0]; // 特殊的instance变量


Public void methodA()


{


synchronized(lock) { //… }


}


// …..


}


注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。


3.将synchronized作用于static 函数,示例代码如下:


Class Foo


{


public synchronized static void methodAAA() // 同步的static 函数


{


//….


}


public void methodBBB()


{


synchronized(Foo.class) // class literal(类名称字面常量)


}


}


代码中的methodBBB()方法是把class literal作为锁的情况,它和同步的static函数产生的效果是一样的,取得的锁很特别,是当前调用这个方法的对象所属的类(Class,而不再是由这个Class产生的某个具体对象了)。


记得在《Effective Java》一书中看到过将 Foo.class和 P1.getClass()用于作同步锁还不一样,不能用P1.getClass()来达到锁这个Class的目的。P1指的是由Foo类产生的对象。


可以推断:如果一个类中定义了一个synchronized的static函数A,也定义了一个synchronized
的instance函数B,那么这个类的同一对象Obj在多线程中分别访问A和B两个方法时,不会构成同步,因为它们的锁都不一样。A方法的锁是Obj这
个对象,而B的锁是Obj所属的那个Class。


小结如下:


搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程序。


还有一些技巧可以让我们对共享资源的同步访问更加安全:


1. 定义private 的instance变量+它的
get方法,而不要定义public/protected的instance变量。如果将变量定义为public,对象在外界可以绕过同步方法的控制而直
接取得它,并改动它。这也是JavaBean的标准实现方式之一。


2.
如果instance变量是一个对象,如数组或ArrayList什么的,那上述方法仍然不安全,因为当外界对象通过get方法拿到这个instance
对象的引用后,又将其指向另一个对象,那么这个private变量也就变了,岂不是很危险。
这个时候就需要将get方法也加上synchronized同步,并且,只返回这个private对象的clone()――这样,调用端得到的就是对象副
本的引用了。

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter