Tuesday, March 31, 2015

Split String to array with whitespace

Example to split String to String array, by whitespace. And also join String array to String.


package javasplitestring;
import java.util.Scanner;
/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSpliteString {
 public static void main(String[] args) {
 String original;
 Scanner scanner = new Scanner(System.in);
 System.out.println("Enter a string:");
 original = scanner.nextLine();
 
 //split String to array splited with whitespace regex
 String[] splittedStringArray = original.split("\\s+");
 System.out.println("length = " + splittedStringArray.length);
 
 for(String s : splittedStringArray){
 System.out.println(s);
 }
 
 //Join the String array to a String using StringBuilder
 StringBuilder stringBuilder = new StringBuilder();
 for(String s : splittedStringArray){
 stringBuilder.append(s);
 }
 System.out.println(stringBuilder);
 }
 
}

Saturday, March 28, 2015

JavaFX example: save TextArea to file, using FileChooser

JavaFX example show how to get content from TextArea, and save it as txt file using FileChooser.


package javafxsavetext;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXSaveText extends Application {
 
 @Override
 public void start(Stage primaryStage) {
 primaryStage.setTitle("java-buddy.blogspot.com");
 Group root = new Group();
 
 TextArea textArea = new TextArea();
 Button buttonSave = new Button("Save");
 
 buttonSave.setOnAction((ActionEvent event) -> {
 FileChooser fileChooser = new FileChooser();
 
 //Set extension filter
 FileChooser.ExtensionFilter extFilter = 
 new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
 fileChooser.getExtensionFilters().add(extFilter);
 
 //Show save file dialog
 File file = fileChooser.showSaveDialog(primaryStage);
 
 if(file != null){
 SaveFile(textArea.getText(), file);
 }
 });
 
 VBox vBox = new VBox();
 vBox.getChildren().addAll(textArea, buttonSave);
 
 root.getChildren().add(vBox);
 
 primaryStage.setScene(new Scene(root, 500, 400));
 primaryStage.show();
 }
 public static void main(String[] args) {
 launch(args);
 }
 private void SaveFile(String content, File file){
 try {
 FileWriter fileWriter;
 
 fileWriter = new FileWriter(file);
 fileWriter.write(content);
 fileWriter.close();
 } catch (IOException ex) {
 Logger.getLogger(JavaFXSaveText.class
 .getName()).log(Level.SEVERE, null, ex);
 }
 
 }
 
}


Related:
- Read text file with JavaFX FileChooser

Friday, March 27, 2015

Reverse String, reverse words order, reverse chars in words

This example show various methods to reverse chars in String, reverse words order, and reverse chars in words but keep words in order.


package javareversestring;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaReverseString {
 public static void main(String[] args) {
 String original;
 Scanner scanner = new Scanner(System.in);
 System.out.println("Enter a string:");
 original = scanner.nextLine();
 
 String reverseString = "";
 for(int i=original.length()-1; i>=0; i--){
 reverseString= reverseString + original.charAt(i);
 }
 System.out.println(reverseString);
 
 System.out.println(new StringBuffer(original).reverse().toString());
 System.out.println(reverseWords(original));
 System.out.println(reverseCharsInWords(original));
 }
 //reverse words
 static private String reverseWords(String src){
 String reversed = "";
 
 Stack<String> stackString = new Stack<>();
 StringTokenizer stringTokenizer = new StringTokenizer(src);
 
 while(stringTokenizer.hasMoreTokens()){
 stackString.push(stringTokenizer.nextToken());
 }
 
 while(!stackString.empty()){
 reversed += stackString.pop() + " ";
 }
 
 return reversed;
 }
 
 //reverse chars in words
 static private String reverseCharsInWords(String src){
 String reversed = "";
 
 List<String> listString = new Stack<>();
 StringTokenizer stringTokenizer = new StringTokenizer(src);
 
 while(stringTokenizer.hasMoreTokens()){
 listString.add(stringTokenizer.nextToken());
 }
 
 while(!listString.isEmpty()){
 String s = listString.remove(0);
 reversed += new StringBuffer(s).reverse().toString() + " ";
 }
 
 return reversed;
 }
}

Thursday, March 26, 2015

Professional Java EE Design Patterns


Master JavaEE Design Pattern implementation to improve your coding efficiency Professional JavaEE Design Patterns is the ultimate guide to working more efficiently with JavaEE, and the only resource that covers both the theory and application of design patterns in solving real-world problems. The authors guide readers through both the fundamentals and little-known secrets of JavaEE6/7, presenting patterns throughout, and demonstrating how they are used in day-to-day programming. As the standard computing platform in community-driven enterprise software, JavaEE provides an API and runtime environment above and beyond JavaSE. Written for the experienced JavaEE developer hoping to improve code quality and efficiency, the book contains time saving patterns, including: Implementation and problem-solving with design patterns Connection between existing non-JavaEE design patterns and new JavaEE concepts Unique organization that prioritizes the most relevant patterns before expanding into advanced techniques Individually-based focus that fully explores each pattern Unlike most JavaEE books that simply offer descriptions or recipes, this book drives home the actual implementation and application to keep square pegs away from round holes. For the programmer looking for a comprehensive guide that is actually useful in the everyday workflow, Professional JavaEE Design Patterns is the definitive resource on the market.

Monday, March 23, 2015

Beginning Java Programming: The Object-Oriented Approach

Beginning Java Programming: The Object-Oriented Approach

A comprehensive Java guide, with samples, exercises, casestudies, and step-by-step instruction

Beginning Java Programming: The Object Oriented Approachis a straightforward resource for getting started with one of theworld's most enduringly popular programming languages. Based onclasses taught by the authors, the book starts with the basics andgradually builds into more advanced concepts. The approach utilizesan integrated development environment that allows readers toimmediately apply what they learn, and includes step-by-stepinstruction with plenty of sample programs. Each chapter containsexercises based on real-world business and educational scenarios,and the final chapter uses case studies to combine several conceptsand put readers' new skills to the test.

Beginning Java Programming: The Object Oriented Approachprovides both the information and the tools beginners need todevelop Java skills, from the general concepts of object-orientedprogramming. Learn to: * Understand the Java language and object-oriented conceptimplementation * Use Java to access and manipulate external data * Make applications accessible to users with GUIs * Streamline workflow with object-oriented patterns

The book is geared for those who want to use Java in an appliedenvironment while learning at the same time. Useful as either acourse text or a stand-alone self-study program, Beginning JavaProgramming is a thorough, comprehensive guide.

Java Cookbook, 3rd edition

Java Cookbook

From lambda expressions and JavaFX 8 to new support for network programming and mobile development, Java 8 brings a wealth of changes. This cookbook helps you get up to speed right away with hundreds of hands-on recipes across a broad range of Java topics. You’ll learn useful techniques for everything from debugging and data structures to GUI development and functional programming.

Each recipe includes self-contained code solutions that you can freely use, along with a discussion of how and why they work. If you are familiar with Java basics, this cookbook will bolster your knowledge of the language in general and Java 8’s main APIs in particular.

Recipes include:
  • Methods for compiling, running, and debugging
  • Manipulating, comparing, and rearranging text
  • Regular expressions for string- and pattern-matching
  • Handling numbers, dates, and times
  • Structuring data with collections, arrays, and other types
  • Object-oriented and functional programming techniques
  • Directory and filesystem operations
  • Working with graphics, audio, and video
  • GUI development, including JavaFX and handlers
  • Network programming on both client and server
  • Database access, using JPA, Hibernate, and JDBC
  • Processing JSON and XML for data storage
  • Multithreading and concurrency