Monday, December 28, 2015

Files.lines() read text file returned by JavaFX FileChooser

Example show how to read all lines from a file returned by JavaFX FileChooser, using Files.lines().


package javafxreadtextfile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXReadTextFile extends Application {
 @Override
 public void start(Stage primaryStage) {
 Button btnLoad = new Button("Load");
 btnLoad.setOnAction(btnLoadEventListener);
 VBox rootBox = new VBox();
 rootBox.getChildren().add(btnLoad);
 
 Scene scene = new Scene(rootBox, 300, 300);
 
 primaryStage.setTitle("java-buddy.blogspot.com");
 primaryStage.setScene(scene);
 primaryStage.show();
 }
 
 EventHandler<ActionEvent> btnLoadEventListener
 = (ActionEvent event) -> {
 FileChooser fileChooser = new FileChooser();
 fileChooser.getExtensionFilters()
 .addAll(
 new FileChooser.ExtensionFilter("TXT files (*.TXT)", "*.TXT"),
 new FileChooser.ExtensionFilter("txt files (*.txt)", "*.txt"));
 
 File file = fileChooser.showOpenDialog(null);
 if (file != null) {
 try {
 Files.lines(file.toPath()).forEach(System.out::println);
 } catch (IOException ex) {
 Logger.getLogger(JavaFXReadTextFile.class.getName())
 .log(Level.SEVERE, null, ex);
 }
 }
 };
 public static void main(String[] args) {
 launch(args);
 }
 
}

Sunday, December 6, 2015

JavaFX FileChooser to open image file, and display on ImageView, run on Ubuntu GNOME 15.10/NetBeans 8.1

Re-test "Use JavaFX FileChooser to open image file, and display on ImageView" on Ubuntu GNOME 15.10/NetBeans 8.1.



package javafxpixel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFxPixel extends Application {
 
 ImageView myImageView;
 
 @Override
 public void start(Stage primaryStage) {
 Button btnLoad = new Button("Load");
 btnLoad.setOnAction(btnLoadEventListener);
 
 myImageView = new ImageView(); 
 
 VBox rootBox = new VBox();
 rootBox.getChildren().addAll(btnLoad, myImageView);
 
 Scene scene = new Scene(rootBox, 300, 300);
 
 primaryStage.setTitle("java-buddy.blogspot.com");
 primaryStage.setScene(scene);
 primaryStage.show();
 }
 /**
 * @param args the command line arguments
 */
 public static void main(String[] args) {
 launch(args);
 }
 
 EventHandler<ActionEvent> btnLoadEventListener
 = new EventHandler<ActionEvent>(){
 
 @Override
 public void handle(ActionEvent t) {
 FileChooser fileChooser = new FileChooser();
 
 //Set extension filter
 FileChooser.ExtensionFilter extFilterJPG = 
 new FileChooser.ExtensionFilter("JPG files (*.JPG)", "*.JPG");
 FileChooser.ExtensionFilter extFilterjpg = 
 new FileChooser.ExtensionFilter("jpg files (*.jpg)", "*.jpg");
 FileChooser.ExtensionFilter extFilterPNG = 
 new FileChooser.ExtensionFilter("PNG files (*.PNG)", "*.PNG");
 FileChooser.ExtensionFilter extFilterpng = 
 new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
 fileChooser.getExtensionFilters()
 .addAll(extFilterJPG, extFilterjpg, extFilterPNG, extFilterpng);
 //Show open file dialog
 File file = fileChooser.showOpenDialog(null);
 
 try {
 BufferedImage bufferedImage = ImageIO.read(file);
 Image image = SwingFXUtils.toFXImage(bufferedImage, null);
 myImageView.setImage(image);
 } catch (IOException ex) {
 Logger.getLogger(JavaFxPixel.class.getName()).log(Level.SEVERE, null, ex);
 }
 }
 };
}

Wednesday, November 11, 2015

Query InterNIC server's whois

Last example show Java example using WhoisClient class to query whois. Alternatively, we can query InterNIC server's whois without WhoisClient class.


package javawhois;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoIs {
 
 private final static String WHO ="google.com";
 private final static String WHOIS_HOST = "whois.internic.net";
 private final static int WHOIS_PORT = 43;
 public static void main(String[] args) {
 int c;
 Socket socket = null; 
 String query = "=" + WHO + "\r\n";
 byte buf[] = query.getBytes();
 
 try {
 socket = new Socket(WHOIS_HOST, WHOIS_PORT);
 InputStream in = socket.getInputStream();
 OutputStream out = socket.getOutputStream(); 
 out.write(buf); 
 out.flush();
 while ((c = in.read()) != -1) { 
 System.out.print((char) c); 
 } 
 System.out.print("\nDone\n");
 } catch (IOException ex) {
 Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
 System.out.print(ex.getMessage());
 } finally {
 if(socket != null){
 try {
 socket.close();
 } catch (IOException ex) {
 Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
 }
 }
 }
 }
 
}

Sunday, November 8, 2015

Java example using WhoisClient class

The WhoisClient class implements the client side of the Internet Whois Protocol defined in RFC 954. To query a host you create a WhoisClient instance, connect to the host, query the host, and finally disconnect from the host. If the whois service you want to query is on a non-standard port, connect to the host at that port.
~ org.apache.commons.net.whois.WhoisClient

Example:
package javawhoisclient;
import java.io.IOException;
import org.apache.commons.net.whois.WhoisClient;
/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoisClient {
 public static void main(String[] args) {
 WhoisClient whois;
 whois = new WhoisClient();
 try {
 whois.connect(WhoisClient.DEFAULT_HOST);
 System.out.println(whois.query("=google.com"));
 whois.disconnect();
 } catch (IOException e) {
 System.err.println("Error I/O exception: " + e.getMessage());
 return;
 }
 }
}



To use WhoisClient class in your program, you have to include library commons-net-3.3 in your code, it can be download here: https://commons.apache.org/proper/commons-net/index.html

This video show how to download and add library commons-net-3.3 to NetBeans IDE.


Next:
- query InterNIC server's whois without WhoisClient class.

Install Netbeans 8.1 0n Ubuntu 15.10

Netbeans IDE 8.1 just released.

This video show how to download and install Netbeans IDE 8.1 on Ubuntu-GNOME 15.10


To install Ubuntu 8.1 on Ubuntu:
- Visit https://netbeans.org/ to download installer-file.
- chmod +x <installer-file-name>.
- run it with command:
./<installer-file-name> to run the installer.

The only special is to select correct path to JDK, 1:40 in the above video.

My JDK was installed with ppa:webupd8team, it's on "/usr/lib/jvm/java-8-oracle".




If you missed the setting JDK path, you still run edit netbeans.conf, to specify netbeans_jdkhome, or run netbeans with --jdkhome option. (ref: http://wiki.netbeans.org/FaqRunningOnJre)

netbeans.conf to set netbeans_jdkhome:



run netbeans with --jdkhome option:


Thursday, November 5, 2015

Java I/O, NIO and NIO.2


Java I/O, NIO and NIO.2

Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes and related types, and the reader/writer classes). Next, you'll learn about NIO's buffer, channel, selector, regular expression, charset, and formatter APIs. Finally, you'll discover NIO.2's offerings in terms of an improved file system interface, asynchronous I/O, and the completion of socket channel functionality.

After reading and using thi book, you'll gain the accelerated knowledge and skill level to really build applications with efficient data access, especially for today's cloud computing streaming data needs.

What you’ll learn
  • How to set permissions and more with the classic File class
  • How to build a flat file database with RandomAccessFile
  • Get to know the byte array, file, filter, and other kinds of streams
  • Master serialization and externalization
  • Discover character streams and their associated writers/readers
  • Tour the buffer APIs
  • Work with channels to transfer buffers to and from I/O services
  • Find out about selectors and readiness selection
  • Master regular expressions
  • Discover charsets and their association with Java's String< class
  • Take advantage of the formatter API to create formatted output
  • How to customize the formatter API
  • Explore the improved file system interface
  • Discover asynchronous I/O and its association with futures and completion handlers
  • Encounter socket channel improvements, including multicasting
Who this book is for
This book is for those experienced with Java, beyond the fundamentals.

Table of Contents
Part 1: Getting Started with I/O
Chapter 1: I/O Basics and APIs
Part 2: Classic I/O APIs
Chapter 2: File
Chapter 3: RandomAccessFile
Chapter 4: Streams
Chapter 5: Writers and Readers
Part 3: New I/O APIs
Chapter 6: Buffers
Chapter 7: Channels
Chapter 8: Selectors
Chapter 9: Regular Expressions
Chapter 10: Charsets
Chapter 11: Formatter and Scanner
Part 4: More New I/O APIs
Chapter 12: File System APIs
Chapter 13: Asynchronous I/O
Chapter 14: Additional NIO.2 APIs
Appendix A: Answers to Review Exercises

Saturday, September 12, 2015

Test-Driven Java Development

Invoke TDD principles for end-to-end application development with Java

About This Book
  • Explore the most popular TDD tools and frameworks and become more proficient in building applications
  • Create applications with better code design, fewer bugs, and higher test coverage, enabling you to get them to market quickly
  • Implement test-driven programming methods into your development workflows
Who This Book Is For
If you're an experienced Java developer and want to implement more effective methods of programming systems and applications, then this book is for you.

What You Will Learn
  • Explore the tools and frameworks required for effective TDD development
  • Perform the Red-Green-Refactor process efficiently, the pillar around which all other TDD procedures are based
  • Master effective unit testing in isolation from the rest of your code
  • Design simple and easily maintainable codes by implementing different techniques
  • Use mocking frameworks and techniques to easily write and quickly execute tests
  • Develop an application to implement behaviour-driven development in conjunction with unit testing
  • Enable and disable features using Feature Toggles
In Detail
Test-driven development (TDD) is a development approach that relies on a test-first procedure that emphasises writing a test before writing the necessary code, and then refactoring the code to optimize it.

The value of performing TDD with Java, one of the most established programming languages, is to improve the productivity of programmers, the maintainability and performance of code, and develop a deeper understanding of the language and how to employ it effectively.

Starting with the basics of TDD and reasons why its adoption is beneficial, this book will take you from the first steps of TDD with Java until you are confident enough to embrace the practice in your day-to-day routine.

You'll be guided through setting up tools, frameworks, and the environment you need, and will dive right in to hands-on exercises with the goal of mastering one practice, tool, or framework at a time. You'll learn about the Red-Green-Refactor procedure, how to write unit tests, and how to use them as executable documentation.

With this book you'll also discover how to design simple and easily maintainable code, work with mocks, utilise behaviour-driven development, refactor old legacy code, and release a half-finished feature to production with feature toggles.

You will finish this book with a deep understanding of the test-driven development methodology and the confidence to apply it to application programming with Java.

Style and approach
An easy-to-follow, hands-on guide to building applications through effective coding practices. This book covers practical examples by introducing different problems, each one designed as a learning exercise to help you understand each aspect of TDD.

Friday, September 4, 2015

JavaFX example - set ViewPort of ImageView


Example to change ViewPort of ImageView, and rotate ImageView.

package javafx_imageview_viewport;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {
 
 @Override
 public void start(Stage primaryStage) {
 
 ImageView imageView1 = new ImageView(new Image("http://goo.gl/kYEQl"));
 
 //Example to rotate ImageView
 Image image2 = new Image("http://goo.gl/kYEQl");
 Rectangle2D viewportRect2 = new Rectangle2D(
 image2.getWidth()/4, 
 image2.getHeight()/4, 
 image2.getWidth()*3/4, 
 image2.getHeight()*3/4);
 ImageView imageView2 = new ImageView(image2);
 imageView2.setViewport(viewportRect2);
 
 Slider sliderRotate = new Slider();
 sliderRotate.setMin(0);
 sliderRotate.setMax(360);
 sliderRotate.setValue(0);
 sliderRotate.valueProperty().addListener(
 (ObservableValue<? extends Number> observable, 
 Number oldValue, Number newValue) -> {
 imageView2.setRotate((double)newValue);
 });
 
 //Example to change ViewPort
 Image image3 = new Image("http://goo.gl/kYEQl");
 Rectangle2D viewportRect3 = new Rectangle2D(
 0, 
 0, 
 image3.getWidth(), 
 image3.getHeight());
 ImageView imageView3 = new ImageView(image3);
 imageView3.setViewport(viewportRect3);
 
 Slider sliderViewPort = new Slider();
 sliderViewPort.setMin(0);
 sliderViewPort.setMax(1.0);
 sliderViewPort.setValue(1.0);
 sliderViewPort.valueProperty().addListener(
 (ObservableValue<? extends Number> observable, 
 Number oldValue, Number newValue) -> {
 Rectangle2D newViewportRect3 = new Rectangle2D(
 0,
 0,
 (double)newValue*image3.getWidth(),
 (double)newValue*image3.getHeight());
 imageView3.setViewport(newViewportRect3);
 });
 
 VBox vBox = new VBox();
 vBox.getChildren().addAll(imageView1, 
 imageView2, sliderRotate,
 imageView3, sliderViewPort);
 
 StackPane root = new StackPane();
 root.getChildren().add(vBox);
 
 Scene scene = new Scene(root, 300, 350);
 
 primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
 primaryStage.setScene(scene);
 primaryStage.show();
 }
 /**
 * @param args the command line arguments
 */
 public static void main(String[] args) {
 launch(args);
 }
 
}


Subscribe to: Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /