home.


Tagged: java-io


Java: Read MANIFEST.MF values from a WAR file

You access your MANIFEST.MF files in a WAR using the ServletContext to grab an input stream:

    InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");
    Manifest manifest = new Manifest(inputStream);    
    Attributes attr = manifest.getMainAttributes();

Attributes will now have all the values in your MANIFEST.MF file. Even ones you’ve added yourself.

Note, anything that messes around with your WAR or MANIFEST.MF file, like running this from Eclipse, may cause this not to work.

java java-io java-manifest

Java: List all the files in a directory based on a regex

If you define a regular expression with Pattern, then use the matcher() and matches() methods on that within a File’s listFiles() method, you will get back a list of the files in the File’s directory based on the regex.

final Pattern p = Pattern.compile(regex);
File[] pagesTemplates = file.listFiles(new FileFilter() {
    @Override
    public boolean accept(File f) {
        return p.matcher(f.getName()).matches();
    }
});
java java-io java-regex

Java: Read a file as a string using Scanner

If you first open a Scanner using a file location wrapped in a FileReader, you can then issue hasNext() and nextLine() to read from that file:

Scanner in = new Scanner(new FileReader("file.txt"));
String s, str="";
while(in.hasNext() && (s=in.nextLine())!=null) str+=s+"\n";
java java-io

Java: Loading a file from the classpath

If you want to load a text file from the classpath, here’s a simple way to do this horrid activity:

 public class TextFileLoader {
     public static String getFileFromClasspath(final String path) {
          final URL r = TextFileLoader.class.getResource(path);
          String result = "";
          try {
              final InputStream is = (InputStream) r.getContent();
              final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
              String l = null;
              while((l=reader.readLine())!=null) {
                result+=l;
              }
          } catch (final Exception e) {
              e.printStackTrace();
              return null;
          }
          return result;
      }
 }
java java-io

java-input-stream-horror

Since I keep forgetting here’s how you get a stream from a URL into a BufferedReader (on which you can run readLine()):

BufferedReader result = new BufferedReader(new  InputStreamReader(url.openStream()));

I hate Java’s I/O.

java java-io

Page 1 of 1