Chia sẻ kiến thức IT ứng dụng: AI, Backend, Frontend, Full Stack, DevOps & Cloud, and More.

Showing posts with label Java Permanent. Show all posts
Showing posts with label Java Permanent. Show all posts

Monday, September 3, 2018

Java Concurrency

1. Java Concurrency from docs.oracle.com
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs. This lesson introduces the platform's basic concurrency support and summarizes some of the high-level APIs in the java.util.concurrent packages.

Friday, May 12, 2017

Gioi thieu Java 8 - Lambda Expressions

Lambda expressions duoc gioi thieu trong Java 8 va duoc coi la mot trong nhung dac diem lon nhat cua Java 8. Lambda expression tang cuong ho tro functional programming, va lam don gian hoa viec viet code.

Syntax

Mot lambda expression duoc dac ta boi cu phap sau −
parameter -> expression body
Following are the important characteristics of a lambda expression −
  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Lambda Expressions Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
  
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
  
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
  
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
  
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
  
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
  
      //without parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
  
      //with parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
  
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
 
   interface MathOperation {
      int operation(int a, int b);
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
 
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope

Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Scope Example

Create the following Java program using editor and save in some folder like C:\>JAVA.
Java8Tester.java
public class Java8Tester {

   final static String salutation = "Hello! ";
   
   public static void main(String args[]){
      GreetingService greetService1 = message -> 
      System.out.println(salutation + message);
      greetService1.sayMessage("Mahesh");
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
Hello! Mahesh

Tuesday, November 22, 2016

Đọc ghi tệp (file) trong java

1. ByteArrayOutputStream
InputStream in = context.openFileInput("datafile.txt");
ByteArrayOutputStream bais = new ByteArrayOutputStream();
byte[] bytes = new byte[8192];
for(int len; (lne = in.read(bytes) > 0;)
   bais.write(bytes, 0, len);
in.close();
return bais.toByteArray();

Friday, October 7, 2016

Đọc, xuất XLS,XLSX,CSV file trong Java

Một số khái niệm:

JExcelAPI, which is a mature, Java-based open source library that lets you read, write, and modify Excel spreadsheets. JExcelAPI's jexcelapi home directory contains a jxl.jar file that contains demos for reading, writing, and copying spreadsheets.
jXLS 1.x provides jxls-reader module to read XLS files and populate Java beans with spreadsheet data.
Jxls v2.x tương tự jXLS 1.x  nhưng đã có nhiều đặc tính mà phiên bản 1.x không có.
HSSF (Horrible SpreadSheet Format) – Use to read and write Microsoft Excel '97(-2007) (XLS) format files.
XSSF (XML SpreadSheet Format) – Used to reading and writting Excel 2007 OOXML - Open Office XML (.xlsx) format files.
SXSSF (package: org.apache.poi.xssf.streaming) is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document. Older rows that are no longer in the window become inaccessible, as they are written to the disk.
HWPF (Horrible Word Processor Format) – to read and write Microsoft Word 97 (DOC) format files.
HSMF (Horrible Stupid Mail Format) – pure Java implementation for Microsoft Outlook MSG files
HDGF (Horrible DiaGram Format) – One of the first pure Java implementation for Microsoft Visio binary files.  
HPSF (Horrible Property Set Format) – For reading “Document Summary” information from Microsoft Office files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HPBF (Horrible PuBlisher Format) – Apache's pure Java implementation for Microsoft Publisher files.
DDF (Dreadful Drawing Format) – Apache POI package for decoding the Microsoft Office Drawing format.
Opencsv is a very simple csv (comma-separated values) parser library for Java. It can dump out SQL tables to CSV:
     java.sql.ResultSet myResultSet = ....
     writer.writeAll(myResultSet, includeHeaders);
and It can bind CSV file to a list of Javabeans using CsvToBean, ColumnPositionMappingStrategy, HeaderColumnNameMappingStrategy classes.
Jasperreport java & JFrame VN apps

Các ví dụ:

Ví dụ dùng thư viện jxl:
WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setEncoding("UTF-8");
        Workbook workbookTemplate = null;
        workbookTemplate = Workbook.getWorkbook(new File(templateRealPath), wbSettings);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableWorkbook copy = Workbook.createWorkbook(outputStream, workbookTemplate);
        workbookTemplate.close();
        WritableSheet sheet = copy.getSheet(0);
        sheet.setName(sheetName);
.....
copy.write(); // Writes out the data held in this workbook in Excel format, to outputStream
        copy.close();       
        OutputStream os = new BufferedOutputStream(new FileOutputStream(realPath));
        outputStream.writeTo(os);
        outputStream.close();

Ví dụ dùng thư viện jxls 1.x:
package jxls.example;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import net.sf.jxls.transformer.XLSTransformer;

/**
 *
 * @author 
 */
public class EmployeeEx {

    public static void main(String[] args) throws Exception {
        Collection staff = new HashSet();
        staff.add(new Employee("Derek", 35, 3000, 0.30));
        staff.add(new Employee("Elsa", 28, 1500, 0.15));
        Map beans = new HashMap();
        beans.put("employee", staff);
        XLSTransformer transformer = new XLSTransformer();
        transformer.transformXLS("employeeTemplate.xls", beans, "employeeOut.xls");
    }
}

Tham khảo:

Apache POI Quick Guide

Wednesday, April 15, 2015

Number literals in Java

Numbers

Numbers in Java can be written in many different forms. Depending on the prefix or suffix we use, we can declare it’s base (binary, hex, octal), and even it’s type (int, long, float).

Alterations in the base:

With literal prefixes we can define 4 different numeric bases, and they are: Octal, Hexadecimal, Decimal and Binary.

Tuesday, March 13, 2012

Java 2D: Composition Rules

In the standard RGB color model, every color is described by its red, green, and blue components. However, it is also convenient to be able to describe areas of an image that are transparent or partially transparent. When you superimpose an image onto an existing drawing, the transparent pixels do not obscure the pixels under them at all, whereas partially transparent pixels are mixed with the pixels under them. Figure 7-23 shows the effect of overlaying a partially transparent rectangle on an image. You can still see the details of the image shine through from under the rectangle.

Figure 7-23. Overlaying a partially transparent rectangle on an image

 

In the Java 2D API, transparency is described by an alpha channel. Each pixel has, in addition to its red, green, and blue color components, an alpha value between 0 (fully transparent) and 1 (fully opaque). For example, the rectangle in Figure 7-23 was filled with a pale yellow color with 50% transparency:
new Color(0.7F, 0.7F, 0.0F, 0.5F);

Monday, March 12, 2012

Java 2D: clipping

1. What isclipping
Clipping is the process of confining paint operations to a limited area or shape.

2. Clipping the Drawing Region
Any Shape object can be used as a clipping path that restricts the portion of the drawing area that will be rendered. The clipping path is part of the Graphics2Dcontext; to set the clip attribute, you call Graphics2D.setClip and pass in the Shape that defines the clipping path you want to use. You can shrink the clipping path by calling the clip method and passing in another Shape; the clip is set to the intersection of the current clip and the specified Shape.

Friday, March 9, 2012

Java 2D: Areas, Strokes, Paint

Areas
An Area object stores and manipulates a resolution-independent description of an enclosed area of 2-dimensional space. Area objects can be transformed and can perform various Constructive Area Geometry (CAG) operations when combined with other Area objects. The CAG operations include area addition, subtraction, intersection, and exclusive or. See the linked method documentation for examples of the various operations.
The Area class implements the Shape interface and provides full support for all of its hit-testing and path iteration facilities, but an Area is more specific than a generalized path in a number of ways..

With the Area class, you can perform boolean operations, such as union, intersection, and subtraction, on any two Shape objects. This technique, often referred to as constructive area geometry, enables you to quickly create complex Shape objects without having to describe each line segment or curve.

Area - Core Java™ 2 Volume II - Advanced Features, Seventh Edition

Sunday, March 4, 2012

Java 2D: Shapes

Here are some of the methods in the Graphics class to draw shapes:
drawLine
drawRectangle
drawRoundRect
draw3DRect
drawPolygon
drawPolyline
drawOval
drawArc
There are also corresponding fill methods. These methods have been in the Graphics class ever since JDK 1.0. The Java 2D API uses a completely different, object-oriented approach. Instead of methods, there are classes:
Line2D
Rectangle2D
RoundRectangle2D
Ellipse2D
Arc2D
QuadCurve2D
CubicCurve2D
GeneralPath
These classes all implement the Shape interface.
Finally, the Point2D class describes a point with an x- and a y-coordinate. Points are useful to define shapes, but they aren't themselves shapes.

Java 2D: Ví dụ ShapesDemo2D.java

GeneralPath class implements the Shape interface and represents a geometric path constructed from lines, and quadratic and cubic curves. The three constructors in this class can create the GeneralPath object with the default winding rule (WIND_NON_ZERO), the given winding rule (WIND_NON_ZERO or WIND_EVEN_ODD), or the specified initial coordinate capacity. The winding rule specifies how the interior of a path is determined.
public void Paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    ...
} 

PHỔ BIẾN

CHUYÊN MỤC

TỔNG LƯỢT XEM