banner



How To Read A File Using Multithreading In Java

It says multiple tasks tin be done at a time but really its non exactly like that.
It will continue the cpu idle time less. Because cpu will take a responsibility to execute many threads if nosotros
Use multithreading.
If its single threaded application and then it might go along the cpu idle for some fourth dimension and hence lowers the performance.

Lets meet the same through example.

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

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

Lets use single threaded program

  1. packet com.kb ;

  2. import coffee.io.BufferedReader ;

  3. import coffee.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 class SingleThreadWriteToFile {

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

  11. long startTime = System.nanoTime ( ) ;

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

  13. File destination = new File ( "East:\\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 ( "Full execution time is " + (stopTime - startTime) ) ;

  22. }

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

  24. try {

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

  26.             writer.write (content) ;

  27.             writer.affluent ( ) ;

  28. } catch ( IOException e) {

  29. // TODO Auto-generated take hold of cake

  30.             east.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.append ( "\north" ) ;

  41. }

  42. } catch ( FileNotFoundException east) {

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

  44.             e.printStackTrace ( ) ;

  45. }

  46. catch ( IOException e) {

  47. // TODO Auto-generated catch block

  48.             due east.printStackTrace ( ) ;

  49. }

  50. render content.toString ( ) ;

  51. }

  52. }

package com.kb;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;  public grade SingleThreadWriteToFile {  	public static void main(String[] args) { 		long startTime = System.nanoTime(); 		 		 		File dir = new File("E:\\java\\sample files"); 		File destination = new File("East:\\java\\sample files\\Destination.txt"); 		File[] files = dir.listFiles(); 		String content; 		for (File file : files) { 		content = readFromFile(file.getAbsolutePath()); 		writeToFile(destination,content); 		} 		long stopTime = System.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)); 			writer.write(content); 			author.flush(); 		} catch (IOException due east) { 			// TODO Car-generated catch cake 			due east.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.append("\north"); 					 				} 			  		} grab (FileNotFoundException e) { 			// TODO Auto-generated catch cake 			e.printStackTrace(); 		} 		catch (IOException eastward) { 			// TODO Auto-generated take hold of block 			e.printStackTrace(); 		} 	return content.toString();	 	}  }

Output is

Now lets utilize multithreading to the above program.

Here how information technology 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 coffee.io.FileWriter ;

  8. import java.io.IOException ;

  9. public class MultithreadingWriteToFile {

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

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

  12. long startTime = System.nanoTime ( ) ;

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

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

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

  16. for ( File file : files) {

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

  18. Thread t = new Thread (w1) ;

  19.             t.setPriority ( Thread.MAX_PRIORITY ) ;

  20.             t.commencement ( ) ;

  21. }

  22. long stopTime = Organization.nanoTime ( ) ;

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

  24. }

  25. }

  26. class Author 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. endeavour {

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

  42.             author.write (content) ;

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

  44.             writer.flush ( ) ;

  45. } grab ( IOException eastward) {

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

  47.             e.printStackTrace ( ) ;

  48. }

  49. }

  50. static Cord readFromFile( String filename) {

  51. StringBuffer content = new StringBuffer ( ) ;

  52. attempt {

  53. String text;

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

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

  56.                     content.suspend (text) ;

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

  58. }

  59. } take hold of ( FileNotFoundException eastward) {

  60. // TODO Car-generated grab block

  61.             eastward.printStackTrace ( ) ;

  62. }

  63. catch ( IOException e) {

  64. // TODO Auto-generated catch block

  65.             eastward.printStackTrace ( ) ;

  66. }

  67. return content.toString ( ) ;

  68. }

  69. }

parcel com.kb;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import coffee.io.IOException;  public class MultithreadingWriteToFile { 	 	public static void main(Cord[] args) { 		Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 		long startTime = System.nanoTime(); 		File dir = new File("Due east:\\coffee\\sample files"); 		File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt"); 		File[] files = dir.listFiles(); 		for (File file : files) { 			Author w1 = new Writer(file, destination); 			Thread t = new Thread(w1); 			t.setPriority(Thread.MAX_PRIORITY); 			t.start(); 			 		} 		long stopTime = Organisation.nanoTime(); 		 	 System.out.println("Total execution time is "+(stopTime - startTime)); 		 	}  }  class 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) { 		try { 			BufferedWriter author = new BufferedWriter(new FileWriter(file,true)); 			writer.write(content); 			writer.write("file content written"); 			author.affluent(); 		} catch (IOException e) { 			// TODO Automobile-generated catch block 			east.printStackTrace(); 		} 		 		 	}  	static String readFromFile(String filename){ 		StringBuffer content = new StringBuffer(); 		endeavor { 			String text; 			BufferedReader reader = new BufferedReader(new FileReader(filename)); 				while((text = reader.readLine())!=goose egg){ 					content.append(text); 					content.append("\n"); 					 				} 			  		} catch (FileNotFoundException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 		} 		catch (IOException eastward) { 			// TODO Auto-generated take hold of block 			e.printStackTrace(); 		} 	return content.toString();	 	}  	 }

Output is

See the time difference between each output is
396687651 nano seconds.

This is how multithreading helps us to attain the functioning.

About the Author

Founder of javainsimpleway.com
I love Coffee and open up source technologies and very much passionate about software development.
I like to share my cognition with others especially on technology 馃檪
I accept given all the examples equally simple as possible to empathise for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find whatsoever mistakes or bugs, Delight drib an electronic mail to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more than updates

How To Read A File Using Multithreading In Java,

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

Posted by: walkerdeboyfaing.blogspot.com

0 Response to "How To Read A File Using Multithreading In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel