Reading Multiple Files Using Threads in Java

Information technology says multiple tasks can be done at a fourth dimension but really its non exactly like that.
It volition go on the cpu idle time less. Considering cpu will accept a responsibility to execute many threads if we
Use multithreading.
If its single threaded awarding then it might go on the cpu idle for some time and hence lowers the performance.

Lets run into the same through instance.

Requirement
Read multiple files from a location and write the content of each file to the same destination file past appending each time.

i accept kept full 3000 files in the source location to read and i will create one thread to read and write ane file content in multithreading scenario whereas in single thread scenario for loop iterates 3000 times to read and write 3000 files.

Lets utilize single threaded programme

  1. package com.kb ;

  2. import java.io.BufferedReader ;

  3. import java.io.BufferedWriter ;

  4. import java.io.File ;

  5. import java.io.FileNotFoundException ;

  6. import coffee.io.FileReader ;

  7. import java.io.FileWriter ;

  8. import java.io.IOException ;

  9. public form SingleThreadWriteToFile {

  10. public static void primary( String [ ] args) {

  11. long startTime = System.nanoTime ( ) ;

  12. File dir = new File ( "E:\\coffee\\sample files" ) ;

  13. File destination = new File ( "E:\\coffee\\sample files\\Destination.txt" ) ;

  14. File [ ] files = dir.listFiles ( ) ;

  15. String content;

  16. for ( File file : files) {

  17.         content = readFromFile(file.getAbsolutePath ( ) ) ;

  18.         writeToFile(destination,content) ;

  19. }

  20. long stopTime = System.nanoTime ( ) ;

  21. System.out.println ( "Total execution time is " + (stopTime - startTime) ) ;

  22. }

  23. individual static void writeToFile( File file,String content) {

  24. attempt {

  25. BufferedWriter author = new BufferedWriter ( new FileWriter (file,true ) ) ;

  26.             writer.write (content) ;

  27.             writer.flush ( ) ;

  28. } grab ( IOException due east) {

  29. // TODO Machine-generated catch cake

  30.             e.printStackTrace ( ) ;

  31. }

  32. }

  33. static String readFromFile( String filename) {

  34. StringBuffer content = new StringBuffer ( ) ;

  35. try {

  36. String text;

  37. BufferedReader reader = new BufferedReader ( new FileReader (filename) ) ;

  38. while ( (text = reader.readLine ( ) ) != nada ) {

  39.                     content.append (text) ;

  40.                     content.suspend ( "\n" ) ;

  41. }

  42. } grab ( FileNotFoundException eastward) {

  43. // TODO Auto-generated take hold of block

  44.             e.printStackTrace ( ) ;

  45. }

  46. catch ( IOException due east) {

  47. // TODO Automobile-generated catch block

  48.             e.printStackTrace ( ) ;

  49. }

  50. render content.toString ( ) ;

  51. }

  52. }

package com.kb;  import java.io.BufferedReader; import coffee.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import coffee.io.FileReader; import java.io.FileWriter; import java.io.IOException;  public class SingleThreadWriteToFile {  	public static void main(Cord[] args) { 		long startTime = System.nanoTime(); 		 		 		File dir = new File("E:\\coffee\\sample files"); 		File destination = new File("E:\\java\\sample files\\Destination.txt"); 		File[] files = dir.listFiles(); 		String content; 		for (File file : files) { 		content = readFromFile(file.getAbsolutePath()); 		writeToFile(destination,content); 		} 		long stopTime = Organisation.nanoTime(); 		 System.out.println("Total execution time is "+(stopTime - startTime));		 	} 	 	private static void writeToFile(File file,String content) { 		try { 			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true)); 			author.write(content); 			writer.affluent(); 		} catch (IOException east) { 			// TODO Automobile-generated take hold of block 			e.printStackTrace(); 		} 		 		 	}  	static String readFromFile(String filename){ 		StringBuffer content = new StringBuffer(); 		endeavor { 			String text; 			BufferedReader reader = new BufferedReader(new FileReader(filename)); 				while((text = reader.readLine())!=null){ 					content.append(text); 					content.suspend("\north"); 					 				} 			  		} catch (FileNotFoundException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 		} 		catch (IOException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 		} 	return content.toString();	 	}  }

Output is

Now lets use multithreading to the above programme.

Here how it goes

  1. package com.kb ;

  2. import java.io.BufferedReader ;

  3. import java.io.BufferedWriter ;

  4. import java.io.File ;

  5. import java.io.FileNotFoundException ;

  6. import java.io.FileReader ;

  7. import java.io.FileWriter ;

  8. import java.io.IOException ;

  9. public grade MultithreadingWriteToFile {

  10. public static void primary( Cord [ ] args) {

  11. Thread.currentThread ( ).setPriority ( Thread.MIN_PRIORITY ) ;

  12. long startTime = Organization.nanoTime ( ) ;

  13. File dir = new File ( "E:\\coffee\\sample files" ) ;

  14. File destination = new File ( "Eastward:\\coffee\\sample files\\DestinationMultiThread.txt" ) ;

  15. File [ ] files = dir.listFiles ( ) ;

  16. for ( File file : files) {

  17. Author w1 = new Author (file, destination) ;

  18. Thread t = new Thread (w1) ;

  19.             t.setPriority ( Thread.MAX_PRIORITY ) ;

  20.             t.start ( ) ;

  21. }

  22. long stopTime = Organisation.nanoTime ( ) ;

  23. Arrangement.out.println ( "Total execution time is " + (stopTime - startTime) ) ;

  24. }

  25. }

  26. grade Writer implements Runnable {

  27. File source;

  28. File destination;

  29. public Author ( File source,File destination) {

  30. this.source = source;

  31. this.destination = destination;

  32. }

  33.     @Override

  34. public void run( ) {

  35. String content;

  36.         content = readFromFile(source.getAbsolutePath ( ) ) ;

  37.         writeToFile(destination,content) ;

  38. }

  39. private static void writeToFile( File file,String content) {

  40. try {

  41. BufferedWriter writer = new BufferedWriter ( new FileWriter (file,truthful ) ) ;

  42.             writer.write (content) ;

  43.             author.write ( "file content written" ) ;

  44.             writer.flush ( ) ;

  45. } catch ( IOException e) {

  46. // TODO Motorcar-generated catch block

  47.             e.printStackTrace ( ) ;

  48. }

  49. }

  50. static String readFromFile( String filename) {

  51. StringBuffer content = new StringBuffer ( ) ;

  52. endeavor {

  53. String text;

  54. BufferedReader reader = new BufferedReader ( new FileReader (filename) ) ;

  55. while ( (text = reader.readLine ( ) ) != null ) {

  56.                     content.append (text) ;

  57.                     content.append ( "\north" ) ;

  58. }

  59. } catch ( FileNotFoundException e) {

  60. // TODO Auto-generated catch block

  61.             due east.printStackTrace ( ) ;

  62. }

  63. catch ( IOException due east) {

  64. // TODO Machine-generated grab block

  65.             e.printStackTrace ( ) ;

  66. }

  67. return content.toString ( ) ;

  68. }

  69. }

bundle com.kb;  import java.io.BufferedReader; import java.io.BufferedWriter; import coffee.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;  public class MultithreadingWriteToFile { 	 	public static void chief(Cord[] args) { 		Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 		long startTime = System.nanoTime(); 		File dir = new File("E:\\java\\sample files"); 		File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt"); 		File[] files = dir.listFiles(); 		for (File file : files) { 			Writer w1 = new Author(file, destination); 			Thread t = new Thread(w1); 			t.setPriority(Thread.MAX_PRIORITY); 			t.start(); 			 		} 		long stopTime = System.nanoTime(); 		 	 System.out.println("Total execution time is "+(stopTime - startTime)); 		 	}  }  grade Writer implements Runnable{ File source; File destination; 	public Writer(File source,File destination) { this.source = source; this.destination = destination; 	} 	@Override 	public void run() { 		Cord content; 		content = 	readFromFile(source.getAbsolutePath()); 		writeToFile(destination,content);		 	} 	 	private static void writeToFile(File file,String content) { 		endeavor { 			BufferedWriter writer = new BufferedWriter(new FileWriter(file,true)); 			author.write(content); 			writer.write("file content written"); 			writer.affluent(); 		} grab (IOException e) { 			// TODO Auto-generated catch block 			east.printStackTrace(); 		} 		 		 	}  	static String readFromFile(Cord filename){ 		StringBuffer content = new StringBuffer(); 		try { 			Cord text; 			BufferedReader reader = new BufferedReader(new FileReader(filename)); 				while((text = reader.readLine())!=null){ 					content.append(text); 					content.append("\northward"); 					 				} 			  		} catch (FileNotFoundException e) { 			// TODO Machine-generated catch block 			e.printStackTrace(); 		} 		catch (IOException e) { 			// TODO Auto-generated grab block 			e.printStackTrace(); 		} 	return content.toString();	 	}  	 }

Output is

Come across the fourth dimension difference between each output is
396687651 nano seconds.

This is how multithreading helps united states of america to achieve the functioning.

About the Author

Founder of javainsimpleway.com
I love Coffee and open source technologies and very much passionate about software development.
I like to share my knowledge with others specially on engineering 🙂
I have given all the examples equally elementary every bit possible to understand for the beginners.
All the code posted on my weblog is developed,compiled and tested in my development environs.
If you lot find any mistakes or bugs, Please drop an email to kb.noesis.sharing@gmail.com

Connect with me on Facebook for more than updates

scotttheiged.blogspot.com

Source: http://javainsimpleway.com/multithreading-in-java/

0 Response to "Reading Multiple Files Using Threads in Java"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel