Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /* ************************************************************************
  #
  #  DivConq
  #
  #  http://divconq.com/
  #
  #  Copyright:
  #    Copyright 2014 eTimeline, LLC. All rights reserved.
  #
 #  License:
 #    See the license.txt file in the project's top-level directory for details.
 #
 #  Authors:
 #    * Andy White
 #
 ************************************************************************ */
 package divconq.util;
 
 import java.io.File;
 
 
 
 public class IOUtil {
    
Read entire text file into a string.

Parameters:
file to read
Returns:
file content if readable, otherwise null
 
     public static String readEntireFile(File file) {
     	// TODO improve to funcresult - update to nio2
     	BufferedReader br = null;
     	
         try {
             StringBuilder sb = new StringBuilder();
             
         	br = new BufferedReader(new FileReader(file));
         	
             String line = br.readLine();
 
             while (line != null) {
                 sb.append(line);
                 sb.append("\n");
                 line = br.readLine();
             }
             
             return sb.toString();
         } 
         catch (IOException x) {
 		} 
         finally {
         	closeQuietly(br);
         }
         
         return null;
     }
    
    
Read entire text file into a string.

Parameters:
file to read
Returns:
file content if readable, otherwise null
 
     public static FuncResult<CharSequencereadEntireFile(Path file) {
     	FuncResult<CharSequenceres = new FuncResult<>();
     	
     	BufferedReader br = null;
     	
         try {
             StringBuilder sb = new StringBuilder();
             
         	br = Files.newBufferedReader(file, Charset.forName("UTF-8"));		
         	
             String line = br.readLine();
 
             while (line != null) {
                 sb.append(line);
                 sb.append("\n");
                 line = br.readLine();
             }
            
            res.setResult(sb);
        } 
        catch (IOException x) {
        	res.error("Unabled to read file " + file + ", error: " + x);
        finally {
        	closeQuietly(br);
        }
        
        return res;
    }
    
    
Read entire sream into a string.

Parameters:
stream to read
Returns:
stream content if readable, otherwise null
    public static String readEntireStream(InputStream stream) {
    	// TODO improve to funcresult - update to nio2
    	BufferedReader br = null;
    	
        try {
            StringBuilder sb = new StringBuilder();
            
        	br = new BufferedReader(new InputStreamReader(stream));
        	
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            
            return sb.toString();
        } 
        catch (IOException x) {
        finally {
        	closeQuietly(br);
        }
        
        return null;
    }
    
	public static OperationResult saveEntireFile(Path destString content) {
		try {
		catch (Exception x) {
			or.error(1, "Error saving file contents: " + x);
		}
		return or;
	}
    
	public static boolean saveEntireFile2(Path destString content) {
		try {
		catch (Exception x) {
			return false;
		}
		return true;
	}
    /*
	public static File safeSave(InputStream in, String dest) {
		File f = new File(dest);
		f.getParentFile().mkdirs();		// TODO check
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
			IOUtils.copy(in, fos);
		catch (Exception x) {
			// TODO 
		}
		finally {
        	IOUtils.closeQuietly(fos);
        	IOUtils.closeQuietly(in);
		}
		return f;
	}
	*/
	public static byte[] charsEncodeAndCompress(CharSequence v) {	
		try {
			byte[] buffer = Utf8Encoder.encode(v);
			cos.write(buffer);
			cos.close();
			bos.close();
			return bos.toByteArray();
		}
		catch (Exception x) {
		}
		return null;
	}
	// TODO improve to funcresult
	public static Memory readEntireFileToMemory(File file) {
		return IOUtil.readEntireFileToMemory(file.toPath());
	}
	// TODO improve to funcresult
	public static Memory readEntireFileToMemory(Path file) {
		try (FileChannel ch = FileChannel.open(file.)) {
            Memory mem = new Memory();		// TODO improve mem to read right from channel...
            
            ByteBuffer bb = ByteBuffer.allocate(4096);
            int amt = ch.read(bb);
            
            while (amt != -1) {
            	bb.flip();
            	mem.write(bb);
            	bb.clear();
            	amt = ch.read(bb);
            }            
            
            mem.setPosition(0);
            
            return mem;
        } 
        catch (IOException x) {
        
        return null;
	}
	static public boolean isLegalFilename(String name) {
		if (StringUtil.isEmpty(name))
			return false;
		if (name.equals(".") || name.contains("..") || name.contains("*") || name.contains("\"") || name.contains("/") || name.contains("\\")
				 || name.contains("<") || name.contains(">") || name.contains(":") || name.contains("?") || name.contains("|"))
			return false;
		return true;
	}
    public static void closeQuietly(Closeable... closeables) {
		if (closeables == null
			return;
		for (Closeable closeable : closeables) { 
			try {
				if (closeable != null
					closeable.close();
			catch (IOException x) {
				// ignore
			}
		}
    }

    
Returns an Iterator for the lines in an InputStream, using the character encoding specified (or default encoding if null).

LineIterator holds a reference to the open InputStream specified here. When you have finished with the iterator you should close the stream to free internal resources. This can be done by closing the stream directly, or by calling divconq.io.LineIterator.close() or divconq.io.LineIterator.closeQuietly(divconq.io.LineIterator).

The recommended usage pattern is:

 try {
   LineIterator it = IOUtils.lineIterator(stream, charset);
   while (it.hasNext()) {
     String line = it.nextLine();
     /// do something with line
   }
 } finally {
   IOUtils.closeQuietly(stream);
 }
 

Parameters:
input the InputStream to read from, not null
encoding the encoding to use, null means platform default
Returns:
an Iterator of the lines in the reader, never null
Throws:
java.lang.IllegalArgumentException if the input is null
java.io.IOException if an I/O error occurs, such as if the encoding is invalid
Since:
2.3
    public static LineIterator lineIterator(InputStream inputCharset encodingthrows IOException {
        return new LineIterator(new InputStreamReader(inputencoding));
    }
 }
New to GrepCode? Check out our FAQ X