forked fromiluwatar/30-seconds-of-java
- Notifications
You must be signed in to change notification settings - Fork0
Collection of reusable tested Java code snippets
License
NotificationsYou must be signed in to change notification settings
java-code-help/java-snippets
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Inspired by30 seconds of code, this is a collection of reusable tested Java code snippets.
Update the sample application with the snippet and add a test for it. After proving that it works update this README.md.
- List directories
- List files in directory
- List files in directory recursively
- Read lines from file to string list
- Zip file
- Zip multiple files
publicstaticvoidquickSort(int[]arr,intleft,intright) {intpivotIndex =left + (right -left) /2;intpivotValue =arr[pivotIndex];inti =left,j =right;while (i <=j) {while (arr[i] <pivotValue) {i++; }while (arr[j] >pivotValue) {j--; }if (i <=j) {inttmp =arr[i];arr[i] =arr[j];arr[j] =tmp;i++;j--; }if (left <i) {quickSort(arr,left,j); }if (right >i) {quickSort(arr,i,right); } } }
publicstatic <T>T[]arrayConcat(T[]first,T[]second) {T[]result =Arrays.copyOf(first,first.length +second.length);System.arraycopy(second,0,result,first.length,second.length);returnresult; }
publicstatic <T>T[]nArrayConcat(T[]first,T[]...rest) {inttotalLength =first.length;for (T[]array :rest) {totalLength +=array.length; }T[]result =Arrays.copyOf(first,totalLength);intoffset =first.length;for (T[]array :rest) {System.arraycopy(array,0,result,offset,array.length);offset +=array.length; }returnresult; }
publicstaticFile[]listDirectories(Stringpath) {returnnewFile(path).listFiles(File::isDirectory); }
publicstaticFile[]listFilesInDirectory(finalFilefolder) {returnfolder.listFiles(File::isFile); }
publicstaticList<File>listAllFiles(Stringpath) {List<File>all =newArrayList<>();File[]list =newFile(path).listFiles();if (list !=null) {// In case of access error, list is nullfor (Filef :list) {if (f.isDirectory()) {all.addAll(listAllFiles(f.getAbsolutePath())); }else {all.add(f.getAbsoluteFile()); } } }returnall; }
publicstaticList<String>readLines(Stringfilename)throwsIOException {returnFiles.readAllLines(newFile(filename).toPath()); }
publicstaticvoidzipFile(StringsrcFilename,StringzipFilename)throwsIOException {FilesrcFile =newFile(srcFilename);try (FileOutputStreamfileOut =newFileOutputStream(zipFilename);ZipOutputStreamzipOut =newZipOutputStream(fileOut);FileInputStreamfileIn =newFileInputStream(srcFile); ) {ZipEntryzipEntry =newZipEntry(srcFile.getName());zipOut.putNextEntry(zipEntry);finalbyte[]bytes =newbyte[1024];intlength;while ((length =fileIn.read(bytes)) >=0) {zipOut.write(bytes,0,length); } } }
publicstaticvoidzipFiles(String[]srcFilenames,StringzipFilename)throwsIOException {try (FileOutputStreamfileOut =newFileOutputStream(zipFilename);ZipOutputStreamzipOut =newZipOutputStream(fileOut); ) {for (inti=0;i<srcFilenames.length;i++) {FilesrcFile =newFile(srcFilenames[i]);try (FileInputStreamfileIn =newFileInputStream(srcFile)) {ZipEntryzipEntry =newZipEntry(srcFile.getName());zipOut.putNextEntry(zipEntry);finalbyte[]bytes =newbyte[1024];intlength;while ((length =fileIn.read(bytes)) >=0) {zipOut.write(bytes,0,length); } } } } }
publicstaticintfibonacci(intn) {if (n <=1)returnn;elsereturnfibonacci(n-1) +fibonacci(n-2); }
publicstaticintfactorial(intnumber) {intresult =1;for (intfactor =2;factor <=number;factor++) {result *=factor; }returnresult; }
publicstaticInteger[]performLottery(intnumNumbers,intnumbersToPick) {List<Integer>numbers =newArrayList<>();for(inti =0;i <numNumbers;i++) {numbers.add(i+1); }Collections.shuffle(numbers);returnnumbers.subList(0,numbersToPick).toArray(newInteger[numbersToPick]); }
publicstaticbooleanisPrime(intnumber) {if (number <3) {returntrue;}// check if n is a multiple of 2if (number %2 ==0) {returnfalse;}// if not, then just check the oddsfor (inti =3;i *i <=number;i +=2) {if (number %i ==0) {returnfalse;}}returntrue;}
publicstaticvoidcaptureScreen(Stringfilename)throwsAWTException,IOException {DimensionscreenSize =Toolkit.getDefaultToolkit().getScreenSize();RectanglescreenRectangle =newRectangle(screenSize);Robotrobot =newRobot();BufferedImageimage =robot.createScreenCapture(screenRectangle);ImageIO.write(image,"png",newFile(filename)); }
publicstaticinthttpGet(URLaddress)throwsIOException {HttpURLConnectioncon = (HttpURLConnection)address.openConnection();returncon.getResponseCode(); }
publicstaticbooleanisPalindrome(Strings) {StringBuildersb =newStringBuilder();for (charc :s.toCharArray()) {if (Character.isLetter(c)) {sb.append(c); } }Stringforward =sb.toString().toLowerCase();Stringbackward =sb.reverse().toString().toLowerCase();returnforward.equals(backward); }
publicstaticStringreverseString(Strings) {returnnewStringBuilder(s).reverse().toString(); }
publicstaticDatestringToDate(Stringdate,Stringformat)throwsParseException {SimpleDateFormatsimpleDateFormat =newSimpleDateFormat(format);returnsimpleDateFormat.parse(date); }
About
Collection of reusable tested Java code snippets
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Languages
- Java100.0%