How to filter the files by file extensions and show the file names
package com.java2novice.files;
import java.io.File;
import java.io.FilenameFilter;
public class MyFileFilter
{
public static void main(String a[])
{
File
file = new File("C:/MyFolder/");
String[]
files = file.list(new FilenameFilter()
{
public boolean accept(File dir,
String name)
{
if(name.toLowerCase().endsWith(".csv"))
{
return true;
}
else
{
return false;
}
}
});
for(String
f:files)
{
System.out.println(f);
}
}
}
How to read file content using byte array
package com.java2novice.files;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileToByteArray
{
public static void main(String a[])
{
String
fileName = "C:/MyFile.txt";
InputStream
is = null;
try
{
is
= new
FileInputStream(fileName);
byte content[] = new byte[2*1024];
int readCount = 0;
while((readCount
= is.read(content)) > 0)
{
System.out.println(new String(content, 0,
readCount-1));
}
}
catch (FileNotFoundException
e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(is
!= null) is.close();
}
catch(Exception ex){}
}
}
}
How to read file content line by line in java
package com.java2novice.files;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadLinesFromFile
{
public static void main(String a[])
{
BufferedReader
br = null;
String
strLine = "";
try
{
br
= new
BufferedReader(
new
FileReader("fileName"));
while(
(strLine = br.readLine()) != null)
{
System.out.println(strLine);
}
}
catch (FileNotFoundException
e)
{
System.err.println("Unable
to find the file: fileName");
}
catch (IOException e)
{
System.err.println("Unable
to read the file: fileName");
}
}
}
How to read property file in static context
package com.java2novice.files;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ClassLoaderFileLoading
{
private static Properties appProp =
null;
static
{
try
{
InputStream
is =
ClassLoaderFileLoading.class.getResourceAsStream("/FileName.properties");
appProp
= new
Properties();
appProp.load(is);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
No comments:
Post a Comment