import java.awt.*;
import java.awt.event.*;
import java.io.*;
@SuppressWarnings("serial")
public class isuru extends Frame implements ActionListener{
String directory;
TextArea textarea;
public isuru(){
this(null, null);
}
public isuru(String filename){
this(null, filename);
}
public isuru(String directory, String filename){
super();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
}
});
textarea = new TextArea("", 24, 80);
textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
textarea.setEditable(false);
this.add("Center", textarea);
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
this.add(p, "South");
Font font = new Font("SansSerif", Font.BOLD, 14);
Button openfile = new Button("Open File");
Button close = new Button("Close");
openfile.addActionListener(this);
openfile.setActionCommand("open");
openfile.setFont(font);
close.addActionListener(this);
close.setActionCommand("close");
close.setFont(font);
p.add(openfile);
p.add(close);
this.pack();
if(directory == null){
File f;
if((filename != null) && (f = new File(filename)).isAbsolute()){
directory = f.getParent();
filename = f.getName();
}else{
directory = System.getProperty("user.dir");
}
this.directory = directory;
setFile(directory, filename);
}
}
public void setFile(String directory, String filename){
if((filename == null) || filename.length() == 0)
return;
File f;
FileReader in = null;
try{
f = new File(directory, filename);
in = new FileReader(f);
char[] buffer = new char[4096];
int len;
textarea.setText("");
while((len = in.read(buffer)) != -1){
String s = new String(buffer,0,len);
textarea.append(s);
}
this.setTitle("FileViewer: "+filename);
textarea.setCaretPosition(0);
}catch(IOException e){
textarea.setText(e.getClass().getName()+ ": " + e.getMessage( ));
this.setTitle("FileViewer: "+filename+ ": I/O Exception");
}finally{
try{
if(in != null)
in.close();
}catch(IOException e){
}
}
}
public void actionPerformed(ActionEvent e){
String cmd = e.getActionCommand();
if(cmd.equals("open")){
FileDialog f = new FileDialog(this, "Open File");
f.setDirectory(directory);
f.show();
directory = f.getDirectory();
setFile(directory, f.getFile());
f.dispose();
}
else if(cmd.equals("close"))
this.dispose();
}
public static void main(String args[]){
Frame f = new isuru((args.length == 1)?args[0]:null);
f.addWindowListener(new WindowAdapter(){
public void windowClosed(WindowEvent e){
System.exit(0);
}
});
f.show();
}
}
C++, Java, Python, PHP, Programming Tips, Linux, Bash Shell Scripting, Security And Tech Stuff
Showing posts with label file. Show all posts
Showing posts with label file. Show all posts
Monday, March 21, 2011
Reading and Displaying Text Files
Sunday, March 20, 2011
File Copy by Java
import java.io.*;
public class isuru{
public static void main(String args[]){
if(args.length != 2){
System.err.println("Usage: java File Copy");
}else{
try{
copy(args[0], args[1]);
}catch(IOException e){
System.err.println(e.getMessage());
}
}
}
public static void copy(String from_name, String to_name) throws IOException {
File from_file = new File(from_name);
File to_file = new File(to_name);
if(!from_file.exists())
abort("No such source file: "+from_name);
if(!from_file.isFile())
abort("Can't copy directory: "+ from_name);
if(!from_file.canRead())
abort("Source file is unreadable"+from_name);
//to_name
if(!to_file.exists()){
if(!to_file.canWrite()){
abort("destination file is unwriteable: "+to_name);
System.out.println("Overwrite existing file "+ to_file.getName()+"?(Y/N): ");
System.out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String response = in.readLine();
if(!response.equals("Y") && !response.equals("y"))
abort("existing file was not overwritten! ");
}
}else{
String parent = to_file.getParent();
if(parent == null)
parent = System.getProperty("user.dir");
File dir = new File(parent);
if(!dir.exists())
abort("destination directory doesn't exist: "+parent);
if(dir.isFile())
abort("destination is not a directory: "+parent);
if(!dir.canWrite())
abort("destination directory is unwritable "+parent);
}
FileInputStream from = null;
FileOutputStream to = null;
try{
from = new FileInputStream(from_file);
to = new FileOutputStream(to_file);
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = from.read(buffer)) != -1)
to.write(buffer,0, bytes_read);
}finally{
if(from != null) try {from.close();} catch(IOException e){;}
if(to != null) try { to.close(); } catch(IOException e ){ ; }
}
}
private static void abort(String msg) throws IOException {
throw new IOException("FileCopy: "+msg);
}
}
Delete File by Java
import java.io.*;
class isuru{
public static void main(String args[]){
if(args.length != 1){
System.err.println("Usage: java Delete");
System.exit(0);
}try{
delete(args[0]);
System.out.println("Deleted successfully!");
}catch(IllegalArgumentException e){
System.err.println(e.getMessage());
}
}
public static void delete(String fileName){
File f = new File(fileName);
if(!f.exists()) fail("Delete: no such file or Directory:"+fileName);
if(!f.canWrite()) fail("Delete: write protected:"+fileName);
if(f.isDirectory()){
String[] files = f.list();
if(files.length > 0){
fail("Delete: directory not empty: "+fileName);
}
}
boolean success = f.delete();
if(!success) fail("Delete: deletion failed! ");
}
protected static void fail(String msg) throws IllegalArgumentException{
throw new IllegalArgumentException(msg);
}
}
Thursday, August 12, 2010
Java - Files and Streams Summary Part 1
1.1 Introduction.
Java.io package provides an extensive library of classes to deal with input and output. Java provides streams as a general mechanism for dealing with data I/O.
There are three kinds of streams.
An output stream - an object that an application use to write a sequence of data, acts as a destination of data.
Entities work as output or input streams.
Creates a new
Methods
Java.io package provides an extensive library of classes to deal with input and output. Java provides streams as a general mechanism for dealing with data I/O.
There are three kinds of streams.
- Byte Streams
- Character Streams
- Buffered Streams
An output stream - an object that an application use to write a sequence of data, acts as a destination of data.
Entities work as output or input streams.
- An array of character or bytes.
- A file
- A pipe
- A network connection
File(String pathname)Creates a new
File instance by converting the given pathname string into an abstract pathname.Methods
- String getName() - Returns the name of the file, excluding directory file resides.
- String getPath() - Returns the (absolute or relative) pathname of the file.
- String getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
- Stirng getCononicalPath() - Platform-dependent. Returns the canonical form of this abstract pathname.
- String getParent() - The parent part of the pathname of this File object is returned if one exists, otherwise the null value is returned.
- boolean isAbsolute() - Whether a File object represents an absolute pathname can be determined using this method.
- long lastModified() - Returns the time that the file denoted by this abstract pathname was last modified.
- long length() - Returns the size (in bytes) of the file represented by the File object.
- boolean equals(Object obj) - This method only compares the pathnames of the File objects, and returns true if they are identical.
- boolean exists() - Return true if specified file or directory is existed.
- boolean isFile() - Return true if the object is a file.
- boolean isDirectory() - Returns true if the object is a directory.
- boolean canRead() - Returns true if the object has read access.
- boolean canWrite() - Returns true if the object has writing access.
- String[] list() - Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
- String[] list(FileNameFilter filter) - Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
1.3 Creating New Files and Directories
- boolean createNewFile() throws IOException - Creates a new, empty file named by the abstract pathname if,and only if, a file with this name does not already exist. Return value is true if the file is created, else false means file is already exists.
- boolean mkdir() - Creates the directory named by this abstract pathname.
- boolean mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
1.4 Rename Files and Directories
- boolean renameTo(File dest) - Renames the file denoted by this abstract pathname.
1.5 Deleting Files and Directories
- boolean delete() - Deletes the file or directory denoted by this abstract pathname.
Subscribe to:
Posts (Atom)