Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#File' - 80 code snippet(s) found

 Sample 1. Method to get all files from a directory recursively

List<File> fileList = new ArrayList();

List<File> read(String dir) throws IOException{
File directory = new File(dir);
File[] fList = directory.listFiles();
for(File file:fList){
if(file.isDirectory()){
read(file.getPath());
} else {
fileList.add(file);
}
}
return fileList;
}

   Like      Feedback     file handling   file   isDirectory()  .getPath()   recursion   java.io.File


 Sample 2. Get the content of a file in a string

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileToString {

public static void main(String[] args) throws IOException {

String line = null;

String wholePage = "";

FileReader fileReader =
new FileReader("/home/vivekvermani/test.txt");

BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {
wholePage = wholePage + line + "
";
}

bufferedReader.close();

System.out.println(wholePage);
}
}

   Like      Feedback     reading file to string  import


 Sample 3. getting file path, absolute path and canonical path

public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}

   Like      Feedback     file  absolute path  canonical path  canonical  file handling  java.io.IOException


 Sample 4. Write to a file using File, FileOutputStream and ObjectOutputStream

class BuggyBread1{
   public static void main(String[] args){
      try {
         BuggyBread1 buggybread1 = new BuggyBread1();
         ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
         objectOutputStream.writeObject(buggybread1);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

   Like      Feedback     File   FileOutputStream   ObjectOutputStream   file handling


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Method to get specific format files from a directory

private Collection<File> getDocAndTextFiles() {
File directory = new File("C:DocDir");
if (directory.exists() && directory.isDirectory()) {
Collection<File> files = FileUtils.listFiles(directory, new String[] { "doc","txt" }, false);
}
return files;
}

   Like      Feedback     file handling  file  directory  FileUtils.listFiles  fileutils


 Sample 6. Load XLS file and print first column using poi XSSFWorkbook

public XSSFWorkbook loadXLSAndPrintFirstColumn(File xlsFile) {
   InputStream inputStream = null;
   try {
      inputStream = new FileInputStream(xlsFile);
   XSSFWorkbook xssFWorkbook = new XSSFWorkbook(inputStream);
      Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
      for (int index = 0; index < sheet.getPhysicalNumberOfRows(); index++) {
      try {
         Row row = sheet.getRow(index);
            System.out.println(row.getCell(0,Row.CREATE_NULL_AS_BLANK).getStringCellValue()));   
      } catch (Exception e) {
      System.out.println("Exception");
   }
}

}

   Like      Feedback     readinf xls  reading excel  apache poi  XSSFWorkbook  InputStream


 Sample 7. Create a new File

File file = new File("xyz.txt");
boolean status = file.createNewFile();

   Like      Feedback     file   file handling  file.createnewfile


 Sample 8. Create a new Directory

File dir = new File("c:xyz");
boolean status = file.mkdir();

   Like      Feedback     file handling  creating new directory  file.mkdir


 Sample 9. Load Properties using Property Class

private static Properties props = null;
   
private static void loadProperties(){
   try {
      if(props == null || props1 == null || props2 == null){
         props = new Properties();
         props.load(new FileInputStream(Constants.PROP_BASE_DIR + Constants.EMPLOYEE_REPORTING_PROP));
      } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

   Like      Feedback     property class  properties  FileInputStream  file handling


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Method to check if the the file exists and not a directory

public static boolean isOleFile(File file)
{
   if ((file == null) || (!file.exists()) || (file.isDirectory())) {
      return false;
   }

   return true;
}

   Like      Feedback     file handling  check if file exists  File class  check if file is a directory  file.isDirectory  file.exists


 Sample 11. Usage of java.io.FileInputStream

FileInputStream fis = new FileInputStream("mypodcast.mp3");
InputStreamRequestEntity re = new InputStreamRequestEntity(fis, "audio/mp3");

   Like      Feedback     ileInputStrea


 Sample 12. Usage of org.apache.hadoop.hdfs.server.namenode.FSEditLog.EditLogFileInputStream

EditLogFileInputStream edits =
new EditLogFileInputStream(getImageFile(sd, NameNodeFile.EDITS));
numEdits = FSEditLog.loadFSEdits(edits);
edits.close();
File editsNew = getImageFile(sd, NameNodeFile.EDITS_NEW);
if (editsNew.exists() && editsNew.length() > 0) {
edits = new EditLogFileInputStream(editsNew);
numEdits += FSEditLog.loadFSEdits(edits);
edits.close();

   Like      Feedback     EditLogFileInputStream  Apache Hadoop


 Sample 13. Usage of MD5MD5CRC32FileChecksum

final MD5MD5CRC32FileChecksum checksum = DFSClient.getFileChecksum(filename, nnproxy, socketFactory, socketTimeout);
MD5MD5CRC32FileChecksum.write(xml, checksum);

   Like      Feedback     MD5MD5CRC32FileChecksum  Apache Hadoop


 Sample 14. Usage of java.nio.channels.FileLock

File lockF = new File(root, STORAGE_FILE_LOCK);
lockF.deleteOnExit();
RandomAccessFile file = new RandomAccessFile(lockF, "rws");
FileLock res = null;
try {
   res = file.getChannel().tryLock();
} catch(OverlappingFileLockException oe) {

}

   Like      Feedback     java.nio  FileLock  input output  file handling


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileStatus

  public synchronized void setPermission(String src, FsPermission permission

) throws IOException {

checkOwner(src);

dir.setPermission(src, permission);

getEditLog().logSync();

if (auditLog.isInfoEnabled()) {

final FileStatus stat = dir.getFileInfo(src);

logAuditEvent(UserGroupInformation.getCurrentUGI(),

Server.getRemoteIp(),

"setPermission", src, null, stat);

}

}


   Like      Feedback      org.apache.hadoop.fs.FileStatus


 Sample 16. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.DistributedFileSystem

  public int metaSave(String[] argv, int idx) throws IOException {

String pathname = argv[idx];

DistributedFileSystem dfs = (DistributedFileSystem) fs;

dfs.metaSave(pathname);

System.out.println("Created file " + pathname + " on server " +

dfs.getUri());

return 0;

}


   Like      Feedback      org.apache.hadoop.hdfs.DistributedFileSystem


 Sample 17. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileSystem

  public static long getTimestamp(Configuration conf, URI cache)

throws IOException {

FileSystem fileSystem = FileSystem.get(cache, conf);

Path filePath = new Path(cache.getPath());



return fileSystem.getFileStatus(filePath).getModificationTime();

}


   Like      Feedback      org.apache.hadoop.fs.FileSystem


 Sample 18. Code Sample / Example / Snippet of org.apache.storm.blobstore.BlobStoreFile

    public void testGetFileLength() throws IOException {

FileSystem fs = dfscluster.getFileSystem();

Map conf = new HashMap();

String validKey = "validkeyBasic";

String testString = "testingblob";

TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);

BlobStoreFile pfile = hbs.write(validKey, false);

SettableBlobMeta meta = new SettableBlobMeta();

meta.set_replication_factor(1);

pfile.setMetadata(meta);

OutputStream ios = pfile.getOutputStream();

ios.write(testString.getBytes(Charset.forName("UTF-8")));

ios.close();

assertEquals(testString.getBytes(Charset.forName("UTF-8")).length, pfile.getFileLength());

}


   Like      Feedback      org.apache.storm.blobstore.BlobStoreFile


 Sample 19. Code Sample / Example / Snippet of java.io.File

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

final String directory = (String) operand.get("directory");

final File base =

(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);

File directoryFile = new File(directory);

if (base != null && !directoryFile.isAbsolute()) {

directoryFile = new File(base, directory);

}

String flavorName = (String) operand.get("flavor");

CsvTable.Flavor flavor;

if (flavorName == null) {

flavor = CsvTable.Flavor.SCANNABLE;

} else {

flavor = CsvTable.Flavor.valueOf(flavorName.toUpperCase());

}

return new CsvSchema(directoryFile, flavor);

}


   Like      Feedback      java.io.File


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Code Sample / Example / Snippet of java.io.FileWriter

    private String createArtifact(String string) throws IOException {

File tmpFile = File.createTempFile("vap", "vm");

tmpFile.delete();

tmpFile.deleteOnExit();



FileWriter writer = new FileWriter(tmpFile);

writer.write(string);

writer.flush();

writer.close();



return tmpFile.toURI().toURL().toExternalForm();

}


   Like      Feedback      java.io.FileWriter


 Sample 21. Code Sample / Example / Snippet of java.nio.channels.FileChannel

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.nio.channels.FileChannel


 Sample 22. Code Sample / Example / Snippet of java.io.FileOutputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileOutputStream


 Sample 23. Code Sample / Example / Snippet of java.io.FileInputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileInputStream


 Sample 24. Code Sample / Example / Snippet of java.io.File

    private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {

ArtifactObject artifact = findArtifact(name, attrs);



if (artifact != null) {

return artifact;

}

else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {

m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));

return null;

}

else {

m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));



File file = storeArtifactContents(name, is);

try {

return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);

}

finally {

file.delete();

}

}

}


   Like      Feedback      java.io.File


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationDefault

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.AnnotationDefault


 Sample 26. Code Sample / Example / Snippet of org.apache.bcel.classfile.Method

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.Method


 Sample 27. Code Sample / Example / Snippet of org.apache.bcel.classfile.SimpleElementValue

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.SimpleElementValue


 Sample 28. Code Sample / Example / Snippet of org.apache.bcel.classfile.JavaClass

    public void testMethodAnnotations() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");

final Method m = getMethod(clazz, "fruit");

final AnnotationDefault a = (AnnotationDefault) findAttribute(

"AnnotationDefault", m.getAttributes());

final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();

assertTrue("Should be STRING but is " + val.getElementValueType(), val

.getElementValueType() == ElementValue.STRING);

assertTrue("Should have default of bananas but default is "

+ val.getValueString(), val.getValueString().equals("bananas"));

}


   Like      Feedback      org.apache.bcel.classfile.JavaClass


 Sample 29. Code Sample / Example / Snippet of org.apache.bcel.classfile.Attribute

    protected String dumpAttributes(final Attribute[] as)

{

final StringBuilder result = new StringBuilder();

result.append("AttributeArray:[");

for (int i = 0; i < as.length; i++)

{

final Attribute attr = as[i];

result.append(attr.toString());

if (i + 1 < as.length) {

result.append(",");

}

}

result.append("]");

return result.toString();

}


   Like      Feedback      org.apache.bcel.classfile.Attribute


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationEntry

    protected String dumpAnnotationEntries(final AnnotationEntry[] as)

{

final StringBuilder result = new StringBuilder();

result.append("[");

for (int i = 0; i < as.length; i++)

{

final AnnotationEntry annotation = as[i];

result.append(annotation.toShortString());

if (i + 1 < as.length) {

result.append(",");

}

}

result.append("]");

return result.toString();

}


   Like      Feedback      org.apache.bcel.classfile.AnnotationEntry


 Sample 31. Code Sample / Example / Snippet of org.apache.bcel.classfile.EnclosingMethod

    public void testCheckMethodLevelNamedInnerClass()

throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");

final ConstantPool pool = clazz.getConstantPool();

final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);

assertTrue("Expected 1 EnclosingMethod attribute but found "

+ encMethodAttrs.length, encMethodAttrs.length == 1);

final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];

final String enclosingClassName = em.getEnclosingClass().getBytes(pool);

final String enclosingMethodName = em.getEnclosingMethod().getName(pool);

assertTrue(

"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "

+ enclosingClassName, enclosingClassName

.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));

assertTrue("Expected method name to be 'main' but was "

+ enclosingMethodName, enclosingMethodName.equals("main"));

}


   Like      Feedback      org.apache.bcel.classfile.EnclosingMethod


 Sample 32. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantPool

    public void testCheckMethodLevelNamedInnerClass()

throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");

final ConstantPool pool = clazz.getConstantPool();

final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);

assertTrue("Expected 1 EnclosingMethod attribute but found "

+ encMethodAttrs.length, encMethodAttrs.length == 1);

final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];

final String enclosingClassName = em.getEnclosingClass().getBytes(pool);

final String enclosingMethodName = em.getEnclosingMethod().getName(pool);

assertTrue(

"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "

+ enclosingClassName, enclosingClassName

.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));

assertTrue("Expected method name to be 'main' but was "

+ enclosingMethodName, enclosingMethodName.equals("main"));

}


   Like      Feedback      org.apache.bcel.classfile.ConstantPool


 Sample 33. Code Sample / Example / Snippet of org.apache.bcel.classfile.ArrayElementValue

    private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)

{

final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];

assertEquals("value", elementValuePair.getNameString());

final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();

final ElementValue[] eva = ev.getElementValuesArray();

assertEquals(nExpectedArrayValues, eva.length);

}


   Like      Feedback      org.apache.bcel.classfile.ArrayElementValue


 Sample 34. Code Sample / Example / Snippet of org.apache.bcel.classfile.ElementValuePair

    private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)

{

final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];

assertEquals("value", elementValuePair.getNameString());

final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();

final ElementValue[] eva = ev.getElementValuesArray();

assertEquals(nExpectedArrayValues, eva.length);

}


   Like      Feedback      org.apache.bcel.classfile.ElementValuePair


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Code Sample / Example / Snippet of org.apache.bcel.classfile.ClassParser

    private void testJar(final File file) throws Exception {

System.out.println(file);

try (JarFile jar = new JarFile(file)) {

final Enumeration<JarEntry> en = jar.entries();

while (en.hasMoreElements()) {

final JarEntry e = en.nextElement();

final String name = e.getName();

if (name.endsWith(".class")) {

try (InputStream in = jar.getInputStream(e)) {

final ClassParser parser = new ClassParser(in, name);

final JavaClass jc = parser.parse();

for (final Method m : jc.getMethods()) {

compare(name, m);

}

}

}

}

}

}


   Like      Feedback      org.apache.bcel.classfile.ClassParser


 Sample 36. Code Sample / Example / Snippet of org.apache.bcel.classfile.Code

    private void compare(final String name, final Method m) {

final Code c = m.getCode();

if (c == null) {

return; // e.g. abstract method

}

final byte[] src = c.getCode();

final InstructionList il = new InstructionList(src);

final byte[] out = il.getByteCode();

if (src.length == out.length) {

assertArrayEquals(name + ": " + m.toString(), src, out);

} else {

System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);

System.out.println(bytesToHex(src));

System.out.println(bytesToHex(out));

for (final InstructionHandle ih : il) {

System.out.println(ih.toString(false));

}

fail("Array comparison failure");

}

}


   Like      Feedback      org.apache.bcel.classfile.Code


 Sample 37. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTable

    public void testB79() throws ClassNotFoundException

{

final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");

final ClassGen gen = new ClassGen(clazz);

final ConstantPoolGen pool = gen.getConstantPool();

final Method m = gen.getMethodAt(2);

final LocalVariableTable lvt = m.getLocalVariableTable();

final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);

final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());

assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());

}


   Like      Feedback      org.apache.bcel.classfile.LocalVariableTable


 Sample 38. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantUtf8

    public static String[] getClassDependencies(ConstantPool pool) {

String[] tempArray = new String[pool.getLength()];

int size = 0;

StringBuilder buf = new StringBuilder();



for (int idx = 0; idx < pool.getLength(); idx++) {

Constant c = pool.getConstant(idx);

if (c != null && c.getTag() == Constants.CONSTANT_Class) {

ConstantUtf8 c1 = (ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex());

buf.setLength(0);

buf.append(c1.getBytes());

for (int n = 0; n < buf.length(); n++) {

if (buf.charAt(n) == '/') {

buf.setCharAt(n, '.');

}

}



tempArray[size++] = buf.toString();

}

}



String[] dependencies = new String[size];

System.arraycopy(tempArray, 0, dependencies, 0, size);

return dependencies;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantUtf8


 Sample 39. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantNameAndType

    private void visitRef(ConstantCP ccp, boolean method) {

String class_name = ccp.getClass(cp);

add(class_name);



ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(ccp.getNameAndTypeIndex(),

Constants.CONSTANT_NameAndType);



String signature = cnat.getSignature(cp);



if (method) {

Type type = Type.getReturnType(signature);



checkType(type);



for (Type type1 : Type.getArgumentTypes(signature)) {

checkType(type1);

}

} else {

checkType(Type.getType(signature));

}

}


   Like      Feedback      org.apache.bcel.classfile.ConstantNameAndType


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Code Sample / Example / Snippet of org.apache.bcel.classfile.Constant

    public String getEnumTypeString()

{

return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))

.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.Constant


 Sample 41. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantInteger

    public int getValueInt()

{

if (super.getElementValueType() != PRIMITIVE_INT) {

throw new RuntimeException(

"Dont call getValueString() on a non STRING ElementValue");

}

final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx);

return c.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantInteger


 Sample 42. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantClass

    public String getEnumTypeString()

{

return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))

.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantClass


 Sample 43. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantCP

    public String getClassName( final ConstantPoolGen cpg ) {

final ConstantPool cp = cpg.getConstantPool();

final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());

final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);

if (className.startsWith("[")) {

return "java.lang.Object";

}

return className.replace('/', '.');

}


   Like      Feedback      org.apache.bcel.classfile.ConstantCP


 Sample 44. Code Sample / Example / Snippet of org.apache.bcel.classfile.Annotations

    public FieldGen(final Field field, final ConstantPoolGen cp) {

this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);

final Attribute[] attrs = field.getAttributes();

for (final Attribute attr : attrs) {

if (attr instanceof ConstantValue) {

setValue(((ConstantValue) attr).getConstantValueIndex());

} else if (attr instanceof Annotations) {

final Annotations runtimeAnnotations = (Annotations)attr;

final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();

for (final AnnotationEntry element : annotationEntries) {

addAnnotationEntry(new AnnotationEntryGen(element,cp,false));

}

} else {

addAttribute(attr);

}

}

}


   Like      Feedback      org.apache.bcel.classfile.Annotations


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantFloat

    public int lookupFloat( final float n ) {

final int bits = Float.floatToIntBits(n);

for (int i = 1; i < index; i++) {

if (constants[i] instanceof ConstantFloat) {

final ConstantFloat c = (ConstantFloat) constants[i];

if (Float.floatToIntBits(c.getBytes()) == bits) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantFloat


 Sample 46. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantString

    public String stringifyValue()

{

final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx);

return cu8.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantString


 Sample 47. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantLong

    public int lookupLong( final long n ) {

for (int i = 1; i < index; i++) {

if (constants[i] instanceof ConstantLong) {

final ConstantLong c = (ConstantLong) constants[i];

if (c.getBytes() == n) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantLong


 Sample 48. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantDouble

    public int lookupDouble( final double n ) {

final long bits = Double.doubleToLongBits(n);

for (int i = 1; i < index; i++) {

if (constants[i] instanceof ConstantDouble) {

final ConstantDouble c = (ConstantDouble) constants[i];

if (Double.doubleToLongBits(c.getBytes()) == bits) {

return i;

}

}

}

return -1;

}


   Like      Feedback      org.apache.bcel.classfile.ConstantDouble


 Sample 49. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantValue

    public void visitField( final Field field ) {

_out.println();

_out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "

+ printType(field.getSignature()) + ", "" + field.getName() + "", _cp);");

final ConstantValue cv = field.getConstantValue();

if (cv != null) {

final String value = cv.toString();

_out.println(" field.setInitValue(" + value + ")");

}

_out.println(" _cg.addField(field.getField());");

}


   Like      Feedback      org.apache.bcel.classfile.ConstantValue


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Code Sample / Example / Snippet of org.apache.bcel.classfile.MethodParameters

    public Attribute copy(final ConstantPool _constant_pool) {

final MethodParameters c = (MethodParameters) clone();

c.parameters = new MethodParameter[parameters.length];



for (int i = 0; i < parameters.length; i++) {

c.parameters[i] = parameters[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.MethodParameters


 Sample 51. Code Sample / Example / Snippet of org.apache.bcel.classfile.Deprecated

    public Attribute copy( final ConstantPool _constant_pool ) {

final Deprecated c = (Deprecated) clone();

if (bytes != null) {

c.bytes = new byte[bytes.length];

System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.Deprecated


 Sample 52. Code Sample / Example / Snippet of org.apache.bcel.classfile.BootstrapMethods

    public BootstrapMethods copy(final ConstantPool _constant_pool) {

final BootstrapMethods c = (BootstrapMethods) clone();

c.bootstrap_methods = new BootstrapMethod[bootstrap_methods.length];



for (int i = 0; i < bootstrap_methods.length; i++) {

c.bootstrap_methods[i] = bootstrap_methods[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.BootstrapMethods


 Sample 53. Code Sample / Example / Snippet of org.apache.bcel.classfile.InnerClasses

    public Attribute copy( final ConstantPool _constant_pool ) {

final InnerClasses c = (InnerClasses) clone();

c.inner_classes = new InnerClass[inner_classes.length];

for (int i = 0; i < inner_classes.length; i++) {

c.inner_classes[i] = inner_classes[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.InnerClasses


 Sample 54. Code Sample / Example / Snippet of org.apache.bcel.classfile.Synthetic

    public Attribute copy( final ConstantPool _constant_pool ) {

final Synthetic c = (Synthetic) clone();

if (bytes != null) {

c.bytes = new byte[bytes.length];

System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.Synthetic


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 55. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTypeTable

    public Attribute copy(final ConstantPool constant_pool) {

final LocalVariableTypeTable c = (LocalVariableTypeTable) clone();



c.local_variable_type_table = new LocalVariable[local_variable_type_table.length];

for (int i = 0; i < local_variable_type_table.length; i++) {

c.local_variable_type_table[i] = local_variable_type_table[i].copy();

}



c.setConstantPool(constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.LocalVariableTypeTable


 Sample 56. Code Sample / Example / Snippet of org.apache.bcel.classfile.Node

  public void jjtAddChild(Node n, int i) {

if (children == null) {

children = new Node[i + 1];

} else if (i >= children.length) {

Node c[] = new Node[i + 1];

System.arraycopy(children, 0, c, 0, children.length);

children = c;

}

children[i] = n;

}


   Like      Feedback      org.apache.bcel.classfile.Node


 Sample 57. Code Sample / Example / Snippet of org.apache.bcel.classfile.ParameterAnnotations

  public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {

final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);

for (final Attribute attribute : attrs) {

if (attribute instanceof ParameterAnnotations) {

final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute;

Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());

}

}

return accumulatedAnnotations.toArray(new ParameterAnnotationEntry[accumulatedAnnotations.size()]);

}


   Like      Feedback      org.apache.bcel.classfile.ParameterAnnotations


 Sample 58. Code Sample / Example / Snippet of org.apache.bcel.classfile.Unknown

    public Attribute copy( final ConstantPool _constant_pool ) {

final Unknown c = (Unknown) clone();

if (bytes != null) {

c.bytes = new byte[bytes.length];

System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.Unknown


 Sample 59. Code Sample / Example / Snippet of org.apache.bcel.classfile.StackMap

    public Attribute copy( final ConstantPool _constant_pool ) {

final StackMap c = (StackMap) clone();

c.map = new StackMapEntry[map.length];

for (int i = 0; i < map.length; i++) {

c.map[i] = map[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.StackMap


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 60. Code Sample / Example / Snippet of org.apache.bcel.classfile.LineNumberTable

    public Attribute copy( final ConstantPool _constant_pool ) {

final LineNumberTable c = (LineNumberTable) clone();

c.line_number_table = new LineNumber[line_number_table.length];

for (int i = 0; i < line_number_table.length; i++) {

c.line_number_table[i] = line_number_table[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.LineNumberTable


 Sample 61. Code Sample / Example / Snippet of org.apache.bcel.classfile.DescendingVisitor

    private void field_and_method_refs_are_valid() {

try {

final JavaClass jc = Repository.lookupClass(myOwner.getClassName());

final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));

v.visit();



} catch (final ClassNotFoundException e) {

throw new AssertionViolatedException("Missing class: " + e, e);

}

}


   Like      Feedback      org.apache.bcel.classfile.DescendingVisitor


 Sample 62. Code Sample / Example / Snippet of org.apache.bcel.classfile.Field

        public void visitGETSTATIC(final GETSTATIC o) {

try {

final String field_name = o.getFieldName(cpg);

final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());

final Field[] fields = jc.getFields();

Field f = null;

for (final Field field : fields) {

if (field.getName().equals(field_name)) {

f = field;

break;

}

}

if (f == null) {

throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());

}



if (! (f.isStatic())) {

constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");

}

} catch (final ClassNotFoundException e) {

throw new AssertionViolatedException("Missing class: " + e, e);

}

}




   Like      Feedback      org.apache.bcel.classfile.Field


 Sample 63. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipFile

    private void removeEntriesFoundInZipFile(final File result, final Map<String, byte[]> entries) throws IOException {

final ZipFile zf = new ZipFile(result);

final Enumeration<ZipArchiveEntry> entriesInPhysicalOrder = zf.getEntriesInPhysicalOrder();

while (entriesInPhysicalOrder.hasMoreElements()){

final ZipArchiveEntry zipArchiveEntry = entriesInPhysicalOrder.nextElement();

final InputStream inputStream = zf.getInputStream(zipArchiveEntry);

final byte[] actual = IOUtils.toByteArray(inputStream);

final byte[] expected = entries.remove(zipArchiveEntry.getName());

assertArrayEquals( "For " + zipArchiveEntry.getName(), expected, actual);

}

zf.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipFile


 Sample 64. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZOutputFile

    public void testReadingBackLZMA2DictSize() throws Exception {

final File output = new File(dir, "lzma2-dictsize.7z");

final SevenZOutputFile outArchive = new SevenZOutputFile(output);

try {

outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));

final SevenZArchiveEntry entry = new SevenZArchiveEntry();

entry.setName("foo.txt");

outArchive.putArchiveEntry(entry);

outArchive.write(new byte[] { 'A' });

outArchive.closeArchiveEntry();

} finally {

outArchive.close();

}



final SevenZFile archive = new SevenZFile(output);

try {

final SevenZArchiveEntry entry = archive.getNextEntry();

final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();

assertEquals(SevenZMethod.LZMA2, m.getMethod());

assertEquals(1 << 20, m.getOptions());

} finally {

archive.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.sevenz.SevenZOutputFile


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 65. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZFile

    public void testAllEmptyFilesArchive() throws Exception {

final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"));

try {

assertNotNull(archive.getNextEntry());

} finally {

archive.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.sevenz.SevenZFile


 Sample 66. GunZip file using Apache Commons


   public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
try {
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}

   Like      Feedback     Zip file using Apache Commons   Compress file using Apache Commons   GunZip file using Apache Commons  Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorOutputStream  IOUtils.copy


 Sample 67. Write a program that reads file using FileReader and BufferedReader

File file = new File("/home/sample.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

   Like      Feedback     File handling  FileReader  BufferedReader


 Sample 68. Maven - Add Dependency in Pom File

<dependencies>
<dependency>
<groupId></groupId>
<artifactId></artifactId>
</dependency>
</dependencies>

   Like      Feedback     maven  pom


 Sample 69. Maven Pom File Template

<project>
<parent>
<groupId></groupId>
<artifactId></artifactId>
<version></version>
</parent>

<modelVersion></modelVersion>

<artifactId></artifactId>
<packaging></packaging>

<name></name>
<url></url>

<properties>
</properties>

<dependencies>
<dependency>
<groupId></groupId>
<artifactId></artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
   <directory></directory>
   <filtering></filtering>
</resource>
</resources>
<plugins>
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
   <artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

   Like      Feedback     maven  pom file  sample pom file


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 70. Maven - SCM ( Source Code Management ) config in POM file

<scm>
<connection></connection>
<developerConnection></developerConnection>
<url></url>
</scm>

   Like      Feedback     maven  pom file  maven scm configuration


 Sample 71. Rename a File

public static void main(String[] args) {
File oldFileName = new File("D:/oldFile.txt");
File newFileName = new File("D:/newFile.txt");
oldFileName.renameTo(newFileName);
}

   Like      Feedback     file io  input output  rename a file  renaming file


 Sample 72. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter

String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];

List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);

File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
   csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);

   Like      Feedback     array of Strings  csv writer


 Sample 73. Rolling File Appender for Log4j


                 ignoreExceptions="false">
      
   %d %p %c - %m %n
      

      

   Like      Feedback     log4j  log4j appender  log4j rolling file appender


 Sample 74. Sample Log4j config with Rolling File Appender within Time Based Triggering Policy

<Configuration status="DEBUG">
<Appenders>
<RollingFile name="File" fileName="logs/xyz.log" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <TimeBasedTriggeringPolicy />
   </RollingFile>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  rolling logs with log4j  TimeBasedTriggeringPolicy


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 75. Sample Log4j config with RollingRandomAccessFile appender and TimeBasedTriggeringPolicy

<Configuration status="INFO">
<Appenders>
<RollingRandomAccessFile name="File" fileName="logs/xyz.log" immediateFlush="true" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <TimeBasedTriggeringPolicy />
   </RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  rolling logs with log4j  TimeBasedTriggeringPolicy  RollingRandomAccessFile


 Sample 76. Sample Log4j config file with RollingRandomAccessFile appender ( Rolling Logs ) and SizeBasedTriggeringPolicy

<Configuration status="INFO">
<Appenders>
<RollingRandomAccessFile name="File" fileName="logs/xyz.log" immediateFlush="true" filePattern="logs/xyz-%d{MM-dd-yyyy}.log.gz">
      <SizeBasedTriggeringPolicy size="250 MB"/>
   </RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

   Like      Feedback     log4j  SizeBasedTriggeringPolicy  RollingRandomAccessFile


 Sample 77. Usage of

import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartResolver;

@EnableWebMvc
@Configuration
public class Application extends WebMvcConfigurerAdapter {
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(500000);
return multipartResolver;
}
}

   Like      Feedback     Usage of MultipartResolver  multipartResolver.setMaxUploadSize(500000)  Setting max file size using Spring multipartResolver


 Sample 78. Get only files from a directory using FileFilter

File dir = new File("C:/Folder");

File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile();
}
});

   Like      Feedback     FileFilter


 Sample 79. Get only sub directories in a directory using FileFilter

File dir = new File("C:/Folder");

File[] subdir = dir.listFiles(new FileFilter() {
   @Override
   public boolean accept(File file) {
      return file.isDirectory();
   }
});

   Like      Feedback     FileFilter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 80. Write a Program to read a file and then count number of words

public class CountwordsinFile {
public static void main(String[] args) throws IOException{
String line = null;

File file = new File("C:Hello.txt");
FileReader fileReader = new FileReader(file);

BufferedReader bufferedReader = new BufferedReader(fileReader);

int countWords = 0;

do {

line = bufferedReader.readLine();
countWords += line.split(" ").length;

} while(line != null);
}
}

   Like      Feedback     file handling  count number of words  code  coding  file handling



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus