Home | FAQ | Contact me

Simple File I/O in Java

Just some quick code...

  private void createFileForTesting( String filename, String content ) throws IOException
  {
    File f = new File( filename );

    if( f.exists() )
      f.delete();

    f.createNewFile();

    FileWriter fw = new FileWriter( f.getAbsoluteFile() );
    BufferedWriter writer = new BufferedWriter( fw );
    writer.write( content );
    writer.close();
  }

  private void deleteJsonFileCreatedForTesting( String filename )
  {
    File f = new File( filename );

    if( f.exists() )
      f.delete();
  }

A useful utility (even as Java 15 is released)...

import java.nio.file.Path;
import java.nio.file.Paths;

import static java.util.Objects.nonNull;

public class Filename
{
  final String filepath;
  final String filename;
  final String parent;
  final String extension;
  final String basename;

  public Filename( final String FILEPATH )
  {
        filepath  = FILEPATH;
    Path path      = Paths.get( FILEPATH );
        parent    = path.getParent().toString();
        filename  = path.getFileName().toString();
    int  dot       = filename.lastIndexOf( '.' );
        extension = ( dot > 0 ) ? filename.substring( dot+1 ) : null;
        basename  = ( nonNull( extension ) )
                    ? filename.substring( 0, filename.length() - extension.length() - 1 )
                    : filename;
  }

  public String filepath()  { return filepath; }
  public String filename()  { return filename; }
  public String parent()    { return parent; }
  public String extension() { return extension; }
  public String basename()  { return basename; }
}

Output running against FILEPATH of /home/russ/Documents/poop.x.dat is:

    filename():  poop.x.dat
    parent():    /home/russ/Documents
    basename():  poop.x
    extension(): dat