NSD TP!

Free File Utility Class for Java

package file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Logger;

public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class.toString());
	
	public static String getWorkingPath() {
		File file = new File("");
		String path = file.getAbsolutePath().toString();
		return path;
	}
	
	public static String readFileAsString(String fileName) throws FileNotFoundException, IOException {
		final StringWriter stringWriter = new StringWriter();
		
		File file = new File(fileName);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		stringWriter.append(new String(bis.readAllBytes()));
		bis.close();
		
		return stringWriter.toString();
	}
	
	public static void writeFile(String fileName, String fileAsString) throws IOException {	
		File file = new File(fileName);
		FileWriter fileWriter = new FileWriter(file);
		fileWriter.write(fileAsString);
		fileWriter.close();
		
		logger.info("Wrote to "+fileName+" with "+fileAsString.getBytes().length+" bytes.");
	}
}

Example use

		try {
			String workingDirectory = FileUtil.getWorkingPath();
			String testfile1 = FileUtil.readFileAsString(workingDirectory+"\\src\\assets\\testfile.txt");
			String testfile2FileName = workingDirectory+"\\src\\assets\\testfile2.txt";
			
			String testDocument = "First line of testfile2\nSecond line of testfile2";
			FileUtil.writeFile(testfile2FileName, testDocument);
			logger.info(testfile1);
			
		} catch (Exception e) {
			logger.severe("Exception: "+e.getMessage());
		}

Updated

package file;

import java.awt.image.RenderedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class.toString());
	
	public static String getWorkingPath() {
		File file = new File("");
		String path = file.getAbsolutePath().toString();
		return path;
	}
	
	public static String readFileAsString(String fileName) throws FileNotFoundException, IOException {
		final StringWriter stringWriter = new StringWriter();
		
		File file = new File(fileName);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		stringWriter.append(new String(bis.readAllBytes()));
		bis.close();
		
		return stringWriter.toString();
	}
	
	public static void writeFile(String fileName, String fileAsString) throws IOException {
		File file = new File(fileName);
		FileWriter fileWriter = new FileWriter(file);
		fileWriter.write(fileAsString);
		fileWriter.close();
		
		logger.info("Wrote to "+fileName+" with "+fileAsString.getBytes().length+" bytes.");
	}
	
	public static void writeBitmap(RenderedImage renderedImage, String fileName) throws IOException {
		File file = new File(fileName);		
		ImageIO.write(renderedImage, "BMP", file);
	}
}

Need to update module-info.java

module ProducerConsumer {
	requires java.logging;
	requires java.desktop;
}

Main File

package main;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import file.FileUtil;

public class Main {
	private static Logger logger = Logger.getLogger(Main.class.toString());	

	public static void main(String[] args) {
		try {
			String workingDirectory = FileUtil.getWorkingPath();
			String testfile1 = FileUtil.readFileAsString(workingDirectory+"\\src\\assets\\testfile.txt");
			String testfile2FileName = workingDirectory+"\\src\\assets\\testfile2.txt";
			String testfile3FileName = workingDirectory+"\\src\\assets\\imageTest.bmp";
			
			String testDocument = "First line of testfile2\nSecond line of testfile2";
			FileUtil.writeFile(testfile2FileName, testDocument);
			logger.info(testfile1);
			
			BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2D = bufferedImage.createGraphics();
			graphics2D.setBackground(Color.BLACK);
			graphics2D.setColor(Color.CYAN);
			graphics2D.draw(new Rectangle(10, 10, 20, 20));
			
			FileUtil.writeBitmap(bufferedImage, testfile3FileName);
			
		} catch (Exception e) {
			logger.severe("Exception: "+e.getMessage());
		}
		
	}
	
	private void startProducerConsumerThreads() {
		ConcurrentLinkedQueue<String> sharedQueue = new ConcurrentLinkedQueue<>();
		AtomicInteger threadCount = new AtomicInteger();
		AtomicInteger consumerThreadCount = new AtomicInteger();
				
		Runnable producerRunnable = () -> {
			String producerId = "producer-"+threadCount.incrementAndGet();
			int count = 0;
			while (true) {
				count++;
				sharedQueue.add(producerId+" : "+count);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					logger.info("Producer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Runnable consumerRunnable = () -> {
			String consumerId = "consumer-"+consumerThreadCount.incrementAndGet();
			while (true) {
				String element;
				
				while (!sharedQueue.isEmpty()) {
					element = sharedQueue.poll();
					logger.info(consumerId+" | "+element);
				}
				try {
					Thread.sleep(250);
				} catch (InterruptedException e) {
					logger.info("Consumer Sleep Interrupted: "+e.getMessage());
				}
			}
		};
		
		Thread producer = new Thread(producerRunnable);
		Thread consumer = new Thread(consumerRunnable);
		
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(6);
		
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 8, 1000, TimeUnit.MILLISECONDS, workQueue);
		
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(producer);
		workQueue.add(consumer);
		workQueue.add(consumer);
		
		workQueue.stream().forEach((task) -> {
			threadPoolExecutor.submit(task);
		});
	}
}

Learned a bit from following website https://blog.idrsolutions.com/how-to-write-bmp-images-in-java/

Easy to non ideally upsell image processing to required to be real time

Blender generates sets of images that can be combined to create videos, potential for a Java library that can combine images into a video

Animation Set Example Class Free for Use

package animation;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.logging.Logger;

import file.FileUtil;

public class AnimatedImageSet {
	private static Logger logger = Logger.getLogger(AnimatedImageSet.class.toString());		
	
	private int width;
	private int length;
	private String directoryOfAnimation;
	private String fileName;
	
	public AnimatedImageSet(int width, int length, String fileName) {
		this.width = width;
		this.length = length;
		this.directoryOfAnimation = "animation-"+System.nanoTime();
		this.fileName = fileName;
		
		String outputDirectory = FileUtil.getWorkingPath()+"\\src\\assets\\"+directoryOfAnimation;
		File file = new File(outputDirectory);
		file.mkdir();			
	}
	
	public void generateAnimation(int length) {
		int x=0,y=0;
		for (int i=0; i<length; i++) {
			createFrame(x,y,fileName,i);
			x=i;
			y=i;
		}
	}
	
	private void createFrame(int x, int y, String fileName, int frameNumber) {
		try {
			String workingDirectory = FileUtil.getWorkingPath();
			String outputFile = workingDirectory+"\\src\\assets\\"+directoryOfAnimation+"\\"+fileName+"-Frame"+frameNumber+".bmp";
			
			BufferedImage bufferedImage = new BufferedImage(width, length, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2D = bufferedImage.createGraphics();
			graphics2D.setBackground(Color.BLACK);
			graphics2D.setColor(Color.CYAN);
			graphics2D.draw(new Rectangle(10, 10, x+10, y+10));
			
			FileUtil.writeBitmap(bufferedImage, outputFile);
			
		} catch (Exception e) {
			logger.severe("Exception: "+e.getMessage());
		}		
	}
}

Example use

			AnimatedImageSet ais = new AnimatedImageSet(100, 100, "testAnimation");
			ais.generateAnimation(10);

I will warn those learning Java society has had a non ideal track record for looking after Open Source developers over time

Where people spend their money speaks volumes

Published by techinfodebug

Flex and Java Developer, Christian, Art, Music, Video, and Vlogging

Leave a comment