Guest User

Untitled

a guest
Nov 20th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. require 'java'
  2. import java.lang.System
  3.  
  4. class File::Temp < File
  5. VERSION = '1.2.2'
  6.  
  7. TMPDIR = System.getProperties["java.io.tmpdir"]
  8.  
  9. attr_reader :path
  10.  
  11. # Creates a new, anonymous, temporary file in your File::Temp::TMPDIR
  12. # directory.
  13. #
  14. # If the +delete+ option is set to true (the default) then the temporary file
  15. # will be deleted automatically as soon as all references to it are closed.
  16. # Otherwise, the file will live on in your File::Temp::TMPDIR path.
  17. #
  18. # If the +delete+ option is set to false, then the file is not deleted. In
  19. # addition, you can supply a string +template+ that the system replaces with
  20. # a unique filename. This template should end with 3 to 6 'X' characters.
  21. # The default template is 'rb_file_temp_XXXXXX'. In this case the temporary
  22. # file lives in the directory where it was created.
  23. #
  24. # Note that when using JRuby the template naming is not as strict, and the
  25. # trailing 'X' characters are simply replaced with the GUID that Java
  26. # generates for unique file names.
  27. #
  28. # Example:
  29. #
  30. # fh = File::Temp.new(true, 'rb_file_temp_XXXXXX') => file
  31. # fh.puts 'hello world'
  32. # fh.close
  33. #
  34. def initialize(delete = true, template = 'rb_file_temp_XXXXXX')
  35. raise TypeError unless template.is_a?(String)
  36.  
  37. # Since Java uses a GUID extension to generate a unique file name
  38. # we'll simply chop off the 'X' characters and let Java do the rest.
  39. template = template.sub(/_X{1,6}/, '_')
  40.  
  41. # For consistency between implementations, convert errors here
  42. # to Errno::EINVAL.
  43. begin
  44. @file = java.io.File.createTempFile(template, nil)
  45. rescue NativeException => err
  46. raise SystemCallError.new(22), template # 22 is EINVAL
  47. end
  48.  
  49. @file.deleteOnExit if delete
  50.  
  51. @path = @file.getName unless delete
  52.  
  53. super(@file.getName, 'wb+')
  54. end
  55.  
  56. # Generates a unique file name.
  57. #
  58. def self.temp_name
  59. file = java.io.File.createTempFile('rb_file_temp_', nil)
  60. file.deleteOnExit
  61. name = file.getName
  62. file.finalize
  63. name
  64. end
  65.  
  66. # Identical to the File#close method except that we also finalize
  67. # the underlying Java File object.
  68. #
  69. def close
  70. super
  71. @file.finalize
  72. end
  73. end
Add Comment
Please, Sign In to add comment