Reqmt : The input file will have a some text, each text delimited by a '$' sign. We need to separate each text to a new file, each new file is appended by'-1', '-2' depending on teh no. of texts it has. If the file has only one text message the original name should remain intact. We need to push the new files into a new path and delete the original ones from the input folder.
public class SplitFile {
public static void main(String[] args) {
/*args = new String[2];
args[0] = "C:/HOMEWARE/reports/swift/"; // input file path
args[1] = "C:/HOMEWARE/reports/extract/"; // output file path*/
try {
File directory = new File(args[0]);
/*Get the list of files in the swift directory*/
String filename[] = directory.list();
String listFilenames=null;
String inputFileName;
String outputFileName;
StringBuffer contents;
/*Iterate the directory for each SWIFT file*/
for (int i = 0; i < filename.length; i++) {
listFilenames = filename[i];
inputFileName=args[0]+listFilenames;
outputFileName=args[1]+listFilenames;
String line = null;
contents=new StringBuffer();
/*Return if the file is not available*/
File is = new File(inputFileName);
if(!is.exists()){
System.err.println("File " + inputFileName+ " not present to begin with!");
break;
}
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
/*Get the contents of the file*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
input.close();
/*Separate each SWIFT message based on the delimiter '$'*/
int count=0;
if(null != contents && contents.length() >0) {
FileOutputStream fop = null;
String str= null;
StringTokenizer token = new StringTokenizer(contents.toString(),"$");
while(token.hasMoreTokens()){
str= token.nextToken().toString();
if(!("\r\n".equals(str))){
count++;
fop = new FileOutputStream(outputFileName + "-"+ count);
fop.write(str.getBytes());
}
}
fop.flush();
fop.close();
}
/*If the file contains only one swift messasge, rename the file to its original name*/
if(count == 1){
File renameFile = new File(outputFileName + "-"+ count);
renameFile.renameTo(new File(outputFileName));
}
/*Delete the original file*/
System.out.println("inputFileName :"+inputFileName);
if(is.delete()){
System.out.println("** File " + inputFileName+ " deleted **");
}else{
System.err.println("Failed to delete " + inputFileName);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not present to begin with!");
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Request not completed due to technical issues. Please contact IT team");
}
}
}
Wednesday, May 26, 2010
Monday, March 22, 2010
java.lang.UnsupportedClassVersionError (Unsupported major.minor version 49.0)
It is caused when the java compiler is not compatible with the code.
Goto Project Proprties -> java Compiler and check your jdk version.
Should solve the problem
Goto Project Proprties -> java Compiler and check your jdk version.
Should solve the problem
Tuesday, January 26, 2010
javax.faces.FacesException: java.lang.ClassNotFoundException: [Ljava.lang.String
I got this error soon after I changed my jdk version to 1.6.
Turned out - since I'm using jdk1.6 unlike 1.5 it will not attempt to load class (java.lang.String) by name by default, hence the exception.
is easily solvable by locating JVM runtime in Eclipse's preferences.
(Window->Preferences->Installed JREs)

now add -Dsun.lang.ClassLoader.allowArraySyntax=true to your VM Arguments.
The error shouldn't persist anymore.
Turned out - since I'm using jdk1.6 unlike 1.5 it will not attempt to load class (java.lang.String) by name by default, hence the exception.
is easily solvable by locating JVM runtime in Eclipse's preferences.
(Window->Preferences->Installed JREs)

now add -Dsun.lang.ClassLoader.allowArraySyntax=true to your VM Arguments.
The error shouldn't persist anymore.
Monday, August 17, 2009
Eclipse build error : Cannot find the class file for java.lang.Object.
The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project
Seems the default JRE is not being set properly to the project that is showing this error.
All you need to do is check the JRE System Library.
Go to the project ->properties->java build path->libraries
Add Library- JRE SYSTEM LIBRARY ->Next
and now choose from the installed jre's
Alternatively you could also add the following to your classpath file :
path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.5.0_15"/>
That should solve the problem.
Seems the default JRE is not being set properly to the project that is showing this error.
All you need to do is check the JRE System Library.
Go to the project ->properties->java build path->libraries
Add Library- JRE SYSTEM LIBRARY ->Next
and now choose from the installed jre's
Alternatively you could also add the following to your classpath file :
That should solve the problem.
Monday, July 27, 2009
Open a new browser from a standalone java program
import java.io.IOException;
public class OpenBrowser
{
public static void displayURL(String url)
{
boolean windows = isWindowsPlatform();
String cmd = null;
try
{
if (windows)
{
// cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
Process p = Runtime.getRuntime().exec(cmd);
}
else
{
// Under Unix, Netscape has to be running for the "-remote"
// command to work. So, we try sending the command and
// check for an exit value. If the exit command is 0,
// it worked, otherwise we need to start the browser.
// cmd = 'netscape -remote openURL(http://www.javaworld.com)'
cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")";
Process p = Runtime.getRuntime().exec(cmd);
try
{
// wait for exit code -- if it's 0, command worked,
// otherwise we need to start the browser up.
int exitCode = p.waitFor();
if (exitCode != 0)
{
// Command failed, start up the browser
// cmd = 'netscape http://www.javaworld.com'
cmd = UNIX_PATH + " " + url;
p = Runtime.getRuntime().exec(cmd);
}
}
catch(InterruptedException x)
{
System.err.println("Error bringing up browser, cmd='" +
cmd + "'");
System.err.println("Caught: " + x);
}
}
}
catch(IOException x)
{
// couldn't exec browser
System.err.println("Could not invoke browser, command=" + cmd);
System.err.println("Caught: " + x);
}
}
/**
* Try to determine whether this application is running under Windows
* or some other platform by examing the "os.name" property.
*
* @return true if this application is running under a Windows OS
*/
public static boolean isWindowsPlatform()
{
String os = "os.name";
if ( os != null && os.startsWith(WIN_ID))
return true;
else
return false;
}
/**
* Simple example.
*/
public static void main(String[] args)
{
displayURL("http://www.google.com");
}
// Used to identify the windows platform.
private static final String WIN_ID = "Windows";
// The default system browser under windows.
private static final String WIN_PATH = "rundll32";
// The flag to display a url.
private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
// The default browser under unix.
private static final String UNIX_PATH = "netscape";
// The flag to display a url.
private static final String UNIX_FLAG = "-remote openURL";
}
Courtesy : here
public class OpenBrowser
{
public static void displayURL(String url)
{
boolean windows = isWindowsPlatform();
String cmd = null;
try
{
if (windows)
{
// cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
Process p = Runtime.getRuntime().exec(cmd);
}
else
{
// Under Unix, Netscape has to be running for the "-remote"
// command to work. So, we try sending the command and
// check for an exit value. If the exit command is 0,
// it worked, otherwise we need to start the browser.
// cmd = 'netscape -remote openURL(http://www.javaworld.com)'
cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")";
Process p = Runtime.getRuntime().exec(cmd);
try
{
// wait for exit code -- if it's 0, command worked,
// otherwise we need to start the browser up.
int exitCode = p.waitFor();
if (exitCode != 0)
{
// Command failed, start up the browser
// cmd = 'netscape http://www.javaworld.com'
cmd = UNIX_PATH + " " + url;
p = Runtime.getRuntime().exec(cmd);
}
}
catch(InterruptedException x)
{
System.err.println("Error bringing up browser, cmd='" +
cmd + "'");
System.err.println("Caught: " + x);
}
}
}
catch(IOException x)
{
// couldn't exec browser
System.err.println("Could not invoke browser, command=" + cmd);
System.err.println("Caught: " + x);
}
}
/**
* Try to determine whether this application is running under Windows
* or some other platform by examing the "os.name" property.
*
* @return true if this application is running under a Windows OS
*/
public static boolean isWindowsPlatform()
{
String os = "os.name";
if ( os != null && os.startsWith(WIN_ID))
return true;
else
return false;
}
/**
* Simple example.
*/
public static void main(String[] args)
{
displayURL("http://www.google.com");
}
// Used to identify the windows platform.
private static final String WIN_ID = "Windows";
// The default system browser under windows.
private static final String WIN_PATH = "rundll32";
// The flag to display a url.
private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
// The default browser under unix.
private static final String UNIX_PATH = "netscape";
// The flag to display a url.
private static final String UNIX_FLAG = "-remote openURL";
}
Courtesy : here
Wednesday, March 25, 2009
Image compressor
Found this piece of code on www.coderanch.com
package com;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageCompression
{
public static void main(String[] args) throws IOException
{
Iterator writers;
BufferedImage bufferedImage;
ImageOutputStream imageOutputStream;
ImageWriter imageWriter;
ImageWriteParam pngparams;
// Read an image from the disk (First Argument)
// bufferedImage = ImageIO.read(new File(args[0]));
bufferedImage = ImageIO.read(new File("C:\\DSC0009111370.JPG"));
// Get all the PNG writers
writers = ImageIO.getImageWritersByFormatName("jpg");
// Fetch the first writer in the list
imageWriter = (ImageWriter) writers.next();
// Just to confirm that the writer in use is CLibPNGImageWriter
System.out.println("\n Writer used : " + imageWriter.getClass().getName() + "\n");
// Specify the parameters according to those the output file will be
// written
// Get Default parameters
pngparams = imageWriter.getDefaultWriteParam();
// Define compression mode
pngparams.setCompressionMode(javax.imageio.ImageWriteParam.MODE_EXPLICIT);
// Define compression quality
pngparams.setCompressionQuality(0.5F);
// Define progressive mode
pngparams.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_COPY_FROM_METADATA);
// Deine destination type - used the ColorModel and SampleModel of the
// Input Image
pngparams.setDestinationType(new ImageTypeSpecifier(bufferedImage.getColorModel(), bufferedImage
.getSampleModel()));
// Set the output stream to Second Argument
// imageOutputStream = ImageIO.createImageOutputStream( new
// FileOutputStream(args[1]) );
imageOutputStream = ImageIO.createImageOutputStream(new FileOutputStream("C:\\new_test.jpg"));
imageWriter.setOutput(imageOutputStream);
// Write the changed Image
imageWriter.write(null, new IIOImage(bufferedImage, null, null), pngparams);
// Close the streams
imageOutputStream.close();
imageWriter.dispose();
}
}
package com;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageCompression
{
public static void main(String[] args) throws IOException
{
Iterator writers;
BufferedImage bufferedImage;
ImageOutputStream imageOutputStream;
ImageWriter imageWriter;
ImageWriteParam pngparams;
// Read an image from the disk (First Argument)
// bufferedImage = ImageIO.read(new File(args[0]));
bufferedImage = ImageIO.read(new File("C:\\DSC0009111370.JPG"));
// Get all the PNG writers
writers = ImageIO.getImageWritersByFormatName("jpg");
// Fetch the first writer in the list
imageWriter = (ImageWriter) writers.next();
// Just to confirm that the writer in use is CLibPNGImageWriter
System.out.println("\n Writer used : " + imageWriter.getClass().getName() + "\n");
// Specify the parameters according to those the output file will be
// written
// Get Default parameters
pngparams = imageWriter.getDefaultWriteParam();
// Define compression mode
pngparams.setCompressionMode(javax.imageio.ImageWriteParam.MODE_EXPLICIT);
// Define compression quality
pngparams.setCompressionQuality(0.5F);
// Define progressive mode
pngparams.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_COPY_FROM_METADATA);
// Deine destination type - used the ColorModel and SampleModel of the
// Input Image
pngparams.setDestinationType(new ImageTypeSpecifier(bufferedImage.getColorModel(), bufferedImage
.getSampleModel()));
// Set the output stream to Second Argument
// imageOutputStream = ImageIO.createImageOutputStream( new
// FileOutputStream(args[1]) );
imageOutputStream = ImageIO.createImageOutputStream(new FileOutputStream("C:\\new_test.jpg"));
imageWriter.setOutput(imageOutputStream);
// Write the changed Image
imageWriter.write(null, new IIOImage(bufferedImage, null, null), pngparams);
// Close the streams
imageOutputStream.close();
imageWriter.dispose();
}
}
Tuesday, March 17, 2009
SPLIT A TEXT FILE TO A SPECIFIED NO. OF SUBFILES
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class SplitFile
{
/*The method splitFile(File source,int noFile,int lsize) splits the file 'source' into 'noFile' no. of individual files, each file having 'lsize' no. of characters*/
public static File[] splitFile(File source,int noFile,int lsize)
{
File[] fileFragments = new File[noFile];
String[] frgfName = new String[noFile];
try{
String sourceFName = source.getName();
long sourceFSize = source.length();
FileInputStream fis = new FileInputStream(source);
System.out.println(noFile);
if (lsize != 0) {
noFile--;
}
System.out.println(noFile);
sourceFName = sourceFName.substring(0, sourceFName.lastIndexOf("."));
int j=0;
for (int i = 1; i <= noFile; i++) {
frgfName[i-1] = "D:\\"+sourceFName + String.valueOf(i)+".txt";
fileFragments[i-1] = new File(frgfName[i-1]);
FileOutputStream fos = new FileOutputStream(fileFragments[i - 1]);
byte[] data = new byte[lsize];
int count = fis.read(data);
fos.write(data);
fos.close();
String frgFileInfo = new String(frgfName[i-1] + "," + String.valueOf(lsize));
}
if (lsize != 0) {
System.out.println(noFile);
frgfName[noFile] = "D:\\"+sourceFName + String.valueOf(noFile+1)+".txt";
fileFragments[noFile] = new File(frgfName[noFile]);
FileOutputStream fos = new FileOutputStream(fileFragments[noFile]);
byte[] data = new byte[lsize];
int count = fis.read(data);
fos.write(data);
fos.close();
String frgFileInfo = new String(frgfName[noFile] + "," + String.valueOf(lsize));
}
} catch (Exception e) {
System.out.println("Error in Splitting:"+e);
return null;
}
return fileFragments;
}
public static void main(String[] args) {
File keyfile = new File("D:/test.txt"); // the path to the source file
File[] resultFiles=null;
resultFiles=splitFile(keyfile,5,30);
for(File fileObj:resultFiles){
System.out.println(fileObj.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class SplitFile
{
/*The method splitFile(File source,int noFile,int lsize) splits the file 'source' into 'noFile' no. of individual files, each file having 'lsize' no. of characters*/
public static File[] splitFile(File source,int noFile,int lsize)
{
File[] fileFragments = new File[noFile];
String[] frgfName = new String[noFile];
try{
String sourceFName = source.getName();
long sourceFSize = source.length();
FileInputStream fis = new FileInputStream(source);
System.out.println(noFile);
if (lsize != 0) {
noFile--;
}
System.out.println(noFile);
sourceFName = sourceFName.substring(0, sourceFName.lastIndexOf("."));
int j=0;
for (int i = 1; i <= noFile; i++) {
frgfName[i-1] = "D:\\"+sourceFName + String.valueOf(i)+".txt";
fileFragments[i-1] = new File(frgfName[i-1]);
FileOutputStream fos = new FileOutputStream(fileFragments[i - 1]);
byte[] data = new byte[lsize];
int count = fis.read(data);
fos.write(data);
fos.close();
String frgFileInfo = new String(frgfName[i-1] + "," + String.valueOf(lsize));
}
if (lsize != 0) {
System.out.println(noFile);
frgfName[noFile] = "D:\\"+sourceFName + String.valueOf(noFile+1)+".txt";
fileFragments[noFile] = new File(frgfName[noFile]);
FileOutputStream fos = new FileOutputStream(fileFragments[noFile]);
byte[] data = new byte[lsize];
int count = fis.read(data);
fos.write(data);
fos.close();
String frgFileInfo = new String(frgfName[noFile] + "," + String.valueOf(lsize));
}
} catch (Exception e) {
System.out.println("Error in Splitting:"+e);
return null;
}
return fileFragments;
}
public static void main(String[] args) {
File keyfile = new File("D:/test.txt"); // the path to the source file
File[] resultFiles=null;
resultFiles=splitFile(keyfile,5,30);
for(File fileObj:resultFiles){
System.out.println(fileObj.getAbsolutePath());
}
}
}
Subscribe to:
Posts (Atom)
REFACTORING
What is Refactoring? A software is built initially to serve a purpose, or address a need. But there is always a need for enhancement, fixin...
-
If you have ever filled an online form, you are bound to have encountered a CAPTCHA. CAPTCHA stands for Completely Automated Public Turin...
-
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on t...
-
Logging is an important aspect of software development, one that is many a time ignored by developers. it's important to have clean an...