OpenShot Library | libopenshot-audio  0.2.0
juce_File.h
1 
2 /** @weakgroup juce_core-files
3  * @{
4  */
5 /*
6  ==============================================================================
7 
8  This file is part of the JUCE library.
9  Copyright (c) 2017 - ROLI Ltd.
10 
11  JUCE is an open source library subject to commercial or open-source
12  licensing.
13 
14  The code included in this file is provided under the terms of the ISC license
15  http://www.isc.org/downloads/software-support-policy/isc-license. Permission
16  To use, copy, modify, and/or distribute this software for any purpose with or
17  without fee is hereby granted provided that the above copyright notice and
18  this permission notice appear in all copies.
19 
20  JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
21  EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
22  DISCLAIMED.
23 
24  ==============================================================================
25 */
26 
27 namespace juce
28 {
29 
30 //==============================================================================
31 /**
32  Represents a local file or directory.
33 
34  This class encapsulates the absolute pathname of a file or directory, and
35  has methods for finding out about the file and changing its properties.
36 
37  To read or write to the file, there are methods for returning an input or
38  output stream.
39 
40  @see FileInputStream, FileOutputStream
41 
42  @tags{Core}
43 */
44 class JUCE_API File final
45 {
46 public:
47  //==============================================================================
48  /** Creates an (invalid) file object.
49 
50  The file is initially set to an empty path, so getFullPathName() will return
51  an empty string.
52 
53  You can use its operator= method to point it at a proper file.
54  */
55  File() = default;
56 
57  /** Creates a file from an absolute path.
58 
59  If the path supplied is a relative path, it is taken to be relative
60  to the current working directory (see File::getCurrentWorkingDirectory()),
61  but this isn't a recommended way of creating a file, because you
62  never know what the CWD is going to be.
63 
64  On the Mac/Linux, the path can include "~" notation for referring to
65  user home directories.
66  */
67  File (const String& absolutePath);
68 
69  /** Creates a copy of another file object. */
70  File (const File&);
71 
72  /** Destructor. */
73  ~File() = default;
74 
75  /** Sets the file based on an absolute pathname.
76 
77  If the path supplied is a relative path, it is taken to be relative
78  to the current working directory (see File::getCurrentWorkingDirectory()),
79  but this isn't a recommended way of creating a file, because you
80  never know what the CWD is going to be.
81 
82  On the Mac/Linux, the path can include "~" notation for referring to
83  user home directories.
84  */
85  File& operator= (const String& newAbsolutePath);
86 
87  /** Copies from another file object. */
88  File& operator= (const File& otherFile);
89 
90  /** Move constructor */
91  File (File&&) noexcept;
92 
93  /** Move assignment operator */
94  File& operator= (File&&) noexcept;
95 
96  //==============================================================================
97  /** Checks whether the file actually exists.
98 
99  @returns true if the file exists, either as a file or a directory.
100  @see existsAsFile, isDirectory
101  */
102  bool exists() const;
103 
104  /** Checks whether the file exists and is a file rather than a directory.
105 
106  @returns true only if this is a real file, false if it's a directory
107  or doesn't exist
108  @see exists, isDirectory
109  */
110  bool existsAsFile() const;
111 
112  /** Checks whether the file is a directory that exists.
113 
114  @returns true only if the file is a directory which actually exists, so
115  false if it's a file or doesn't exist at all
116  @see exists, existsAsFile
117  */
118  bool isDirectory() const;
119 
120  /** Checks whether the path of this file represents the root of a file system,
121  irrespective of its existence.
122 
123  This will return true for "C:", "D:", etc on Windows and "/" on other
124  platforms.
125  */
126  bool isRoot() const;
127 
128  /** Returns the size of the file in bytes.
129 
130  @returns the number of bytes in the file, or 0 if it doesn't exist.
131  */
132  int64 getSize() const;
133 
134  /** Utility function to convert a file size in bytes to a neat string description.
135 
136  So for example 100 would return "100 bytes", 2000 would return "2 KB",
137  2000000 would produce "2 MB", etc.
138  */
139  static String descriptionOfSizeInBytes (int64 bytes);
140 
141  //==============================================================================
142  /** Returns the complete, absolute path of this file.
143 
144  This includes the filename and all its parent folders. On Windows it'll
145  also include the drive letter prefix; on Mac or Linux it'll be a complete
146  path starting from the root folder.
147 
148  If you just want the file's name, you should use getFileName() or
149  getFileNameWithoutExtension().
150 
151  @see getFileName, getRelativePathFrom
152  */
153  const String& getFullPathName() const noexcept { return fullPath; }
154 
155  /** Returns the last section of the pathname.
156 
157  Returns just the final part of the path - e.g. if the whole path
158  is "/moose/fish/foo.txt" this will return "foo.txt".
159 
160  For a directory, it returns the final part of the path - e.g. for the
161  directory "/moose/fish" it'll return "fish".
162 
163  If the filename begins with a dot, it'll return the whole filename, e.g. for
164  "/moose/.fish", it'll return ".fish"
165 
166  @see getFullPathName, getFileNameWithoutExtension
167  */
168  String getFileName() const;
169 
170  /** Creates a relative path that refers to a file relatively to a given directory.
171 
172  e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
173  would return "../../foo.txt".
174 
175  If it's not possible to navigate from one file to the other, an absolute
176  path is returned. If the paths are invalid, an empty string may also be
177  returned.
178 
179  @param directoryToBeRelativeTo the directory which the resultant string will
180  be relative to. If this is actually a file rather than
181  a directory, its parent directory will be used instead.
182  If it doesn't exist, it's assumed to be a directory.
183  @see getChildFile, isAbsolutePath
184  */
185  String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
186 
187  //==============================================================================
188  /** Returns the file's extension.
189 
190  Returns the file extension of this file, also including the dot.
191 
192  e.g. "/moose/fish/foo.txt" would return ".txt"
193 
194  @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
195  */
196  String getFileExtension() const;
197 
198  /** Checks whether the file has a given extension.
199 
200  @param extensionToTest the extension to look for - it doesn't matter whether or
201  not this string has a dot at the start, so ".wav" and "wav"
202  will have the same effect. To compare with multiple extensions, this
203  parameter can contain multiple strings, separated by semi-colons -
204  so, for example: hasFileExtension (".jpeg;png;gif") would return
205  true if the file has any of those three extensions.
206 
207  @see getFileExtension, withFileExtension, getFileNameWithoutExtension
208  */
209  bool hasFileExtension (StringRef extensionToTest) const;
210 
211  /** Returns a version of this file with a different file extension.
212 
213  e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
214 
215  @param newExtension the new extension, either with or without a dot at the start (this
216  doesn't make any difference). To get remove a file's extension altogether,
217  pass an empty string into this function.
218 
219  @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
220  */
221  File withFileExtension (StringRef newExtension) const;
222 
223  /** Returns the last part of the filename, without its file extension.
224 
225  e.g. for "/moose/fish/foo.txt" this will return "foo".
226 
227  @see getFileName, getFileExtension, hasFileExtension, withFileExtension
228  */
229  String getFileNameWithoutExtension() const;
230 
231  //==============================================================================
232  /** Returns a 32-bit hash-code that identifies this file.
233 
234  This is based on the filename. Obviously it's possible, although unlikely, that
235  two files will have the same hash-code.
236  */
237  int hashCode() const;
238 
239  /** Returns a 64-bit hash-code that identifies this file.
240 
241  This is based on the filename. Obviously it's possible, although unlikely, that
242  two files will have the same hash-code.
243  */
244  int64 hashCode64() const;
245 
246  //==============================================================================
247  /** Returns a file that represents a relative (or absolute) sub-path of the current one.
248 
249  This will find a child file or directory of the current object.
250 
251  e.g.
252  File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
253  File ("/moose/fish").getChildFile ("haddock/foo.txt") will produce "/moose/fish/haddock/foo.txt".
254  File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
255 
256  If the string is actually an absolute path, it will be treated as such, e.g.
257  File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
258 
259  @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
260  */
261  File getChildFile (StringRef relativeOrAbsolutePath) const;
262 
263  /** Returns a file which is in the same directory as this one.
264 
265  This is equivalent to getParentDirectory().getChildFile (name).
266 
267  @see getChildFile, getParentDirectory
268  */
269  File getSiblingFile (StringRef siblingFileName) const;
270 
271  //==============================================================================
272  /** Returns the directory that contains this file or directory.
273 
274  e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
275 
276  If you are already at the root directory ("/" or "C:") then this method will
277  return the root directory.
278  */
279  File getParentDirectory() const;
280 
281  /** Checks whether a file is somewhere inside a directory.
282 
283  Returns true if this file is somewhere inside a subdirectory of the directory
284  that is passed in. Neither file actually has to exist, because the function
285  just checks the paths for similarities.
286 
287  e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
288  File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
289  */
290  bool isAChildOf (const File& potentialParentDirectory) const;
291 
292  //==============================================================================
293  /** Chooses a filename relative to this one that doesn't already exist.
294 
295  If this file is a directory, this will return a child file of this
296  directory that doesn't exist, by adding numbers to a prefix and suffix until
297  it finds one that isn't already there.
298 
299  If the prefix + the suffix doesn't exist, it won't bother adding a number.
300 
301  e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
302  return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
303 
304  @param prefix the string to use for the filename before the number
305  @param suffix the string to add to the filename after the number
306  @param putNumbersInBrackets if true, this will create filenames in the
307  format "prefix(number)suffix", if false, it will leave the
308  brackets out.
309  */
310  File getNonexistentChildFile (const String& prefix,
311  const String& suffix,
312  bool putNumbersInBrackets = true) const;
313 
314  /** Chooses a filename for a sibling file to this one that doesn't already exist.
315 
316  If this file doesn't exist, this will just return itself, otherwise it
317  will return an appropriate sibling that doesn't exist, e.g. if a file
318  "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
319 
320  @param putNumbersInBrackets whether to add brackets around the numbers that
321  get appended to the new filename.
322  */
323  File getNonexistentSibling (bool putNumbersInBrackets = true) const;
324 
325  //==============================================================================
326  /** Compares the pathnames for two files. */
327  bool operator== (const File&) const;
328  /** Compares the pathnames for two files. */
329  bool operator!= (const File&) const;
330  /** Compares the pathnames for two files. */
331  bool operator< (const File&) const;
332  /** Compares the pathnames for two files. */
333  bool operator> (const File&) const;
334 
335  //==============================================================================
336  /** Checks whether a file can be created or written to.
337 
338  @returns true if it's possible to create and write to this file. If the file
339  doesn't already exist, this will check its parent directory to
340  see if writing is allowed.
341  @see setReadOnly
342  */
343  bool hasWriteAccess() const;
344 
345  /** Changes the write-permission of a file or directory.
346 
347  @param shouldBeReadOnly whether to add or remove write-permission
348  @param applyRecursively if the file is a directory and this is true, it will
349  recurse through all the subfolders changing the permissions
350  of all files
351  @returns true if it manages to change the file's permissions.
352  @see hasWriteAccess
353  */
354  bool setReadOnly (bool shouldBeReadOnly,
355  bool applyRecursively = false) const;
356 
357  /** Changes the execute-permissions of a file.
358 
359  @param shouldBeExecutable whether to add or remove execute-permission
360  @returns true if it manages to change the file's permissions.
361  */
362  bool setExecutePermission (bool shouldBeExecutable) const;
363 
364  /** Returns true if this file is a hidden or system file.
365  The criteria for deciding whether a file is hidden are platform-dependent.
366  */
367  bool isHidden() const;
368 
369  /** Returns a unique identifier for the file, if one is available.
370 
371  Depending on the OS and file-system, this may be a unix inode number or
372  a win32 file identifier, or 0 if it fails to find one. The number will
373  be unique on the filesystem, but not globally.
374  */
375  uint64 getFileIdentifier() const;
376 
377  //==============================================================================
378  /** Returns the last modification time of this file.
379 
380  @returns the time, or an invalid time if the file doesn't exist.
381  @see setLastModificationTime, getLastAccessTime, getCreationTime
382  */
383  Time getLastModificationTime() const;
384 
385  /** Returns the last time this file was accessed.
386 
387  @returns the time, or an invalid time if the file doesn't exist.
388  @see setLastAccessTime, getLastModificationTime, getCreationTime
389  */
390  Time getLastAccessTime() const;
391 
392  /** Returns the time that this file was created.
393 
394  @returns the time, or an invalid time if the file doesn't exist.
395  @see getLastModificationTime, getLastAccessTime
396  */
397  Time getCreationTime() const;
398 
399  /** Changes the modification time for this file.
400 
401  @param newTime the time to apply to the file
402  @returns true if it manages to change the file's time.
403  @see getLastModificationTime, setLastAccessTime, setCreationTime
404  */
405  bool setLastModificationTime (Time newTime) const;
406 
407  /** Changes the last-access time for this file.
408 
409  @param newTime the time to apply to the file
410  @returns true if it manages to change the file's time.
411  @see getLastAccessTime, setLastModificationTime, setCreationTime
412  */
413  bool setLastAccessTime (Time newTime) const;
414 
415  /** Changes the creation date for this file.
416 
417  @param newTime the time to apply to the file
418  @returns true if it manages to change the file's time.
419  @see getCreationTime, setLastModificationTime, setLastAccessTime
420  */
421  bool setCreationTime (Time newTime) const;
422 
423  /** If possible, this will try to create a version string for the given file.
424 
425  The OS may be able to look at the file and give a version for it - e.g. with
426  executables, bundles, dlls, etc. If no version is available, this will
427  return an empty string.
428  */
429  String getVersion() const;
430 
431  //==============================================================================
432  /** Creates an empty file if it doesn't already exist.
433 
434  If the file that this object refers to doesn't exist, this will create a file
435  of zero size.
436 
437  If it already exists or is a directory, this method will do nothing.
438 
439  If the parent directories of the File do not exist then this method will
440  recursively create the parent directories.
441 
442  @returns a result to indicate whether the file was created successfully,
443  or an error message if it failed.
444  @see createDirectory
445  */
446  Result create() const;
447 
448  /** Creates a new directory for this filename.
449 
450  This will try to create the file as a directory, and will also create
451  any parent directories it needs in order to complete the operation.
452 
453  @returns a result to indicate whether the directory was created successfully, or
454  an error message if it failed.
455  @see create
456  */
457  Result createDirectory() const;
458 
459  /** Deletes a file.
460 
461  If this file is actually a directory, it may not be deleted correctly if it
462  contains files. See deleteRecursively() as a better way of deleting directories.
463 
464  If this file is a symlink, then the symlink will be deleted and not the target
465  of the symlink.
466 
467  @returns true if the file has been successfully deleted (or if it didn't exist to
468  begin with).
469  @see deleteRecursively
470  */
471  bool deleteFile() const;
472 
473  /** Deletes a file or directory and all its subdirectories.
474 
475  If this file is a directory, this will try to delete it and all its subfolders. If
476  it's just a file, it will just try to delete the file.
477 
478 
479  @param followSymlinks If true, then any symlink pointing to a directory will also
480  recursively delete the contents of that directory
481  @returns true if the file and all its subfolders have been successfully
482  deleted (or if it didn't exist to begin with).
483  @see deleteFile
484  */
485  bool deleteRecursively (bool followSymlinks = false) const;
486 
487  /** Moves this file or folder to the trash.
488 
489  @returns true if the operation succeeded. It could fail if the trash is full, or
490  if the file is write-protected, so you should check the return value
491  and act appropriately.
492  */
493  bool moveToTrash() const;
494 
495  /** Moves or renames a file.
496 
497  Tries to move a file to a different location.
498  If the target file already exists, this will attempt to delete it first, and
499  will fail if this can't be done.
500 
501  Note that the destination file isn't the directory to put it in, it's the actual
502  filename that you want the new file to have.
503 
504  Also note that on some OSes (e.g. Windows), moving files between different
505  volumes may not be possible.
506 
507  @returns true if the operation succeeds
508  */
509  bool moveFileTo (const File& targetLocation) const;
510 
511  /** Copies a file.
512 
513  Tries to copy a file to a different location.
514  If the target file already exists, this will attempt to delete it first, and
515  will fail if this can't be done.
516 
517  @returns true if the operation succeeds
518  */
519  bool copyFileTo (const File& targetLocation) const;
520 
521  /** Replaces a file.
522 
523  Replace the file in the given location, assuming the replaced files identity.
524  Depending on the file system this will preserve file attributes such as
525  creation date, short file name, etc.
526 
527  If replacement succeeds the original file is deleted.
528 
529  @returns true if the operation succeeds
530  */
531  bool replaceFileIn (const File& targetLocation) const;
532 
533  /** Copies a directory.
534 
535  Tries to copy an entire directory, recursively.
536 
537  If this file isn't a directory or if any target files can't be created, this
538  will return false.
539 
540  @param newDirectory the directory that this one should be copied to. Note that this
541  is the name of the actual directory to create, not the directory
542  into which the new one should be placed, so there must be enough
543  write privileges to create it if it doesn't exist. Any files inside
544  it will be overwritten by similarly named ones that are copied.
545  */
546  bool copyDirectoryTo (const File& newDirectory) const;
547 
548  //==============================================================================
549  /** Used in file searching, to specify whether to return files, directories, or both.
550  */
552  {
553  findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
554  findFiles = 2, /**< Use this flag to indicate that you want to find files. */
555  findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
556  ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
557  };
558 
559  /** Searches this directory for files matching a wildcard pattern.
560 
561  Assuming that this file is a directory, this method will search it
562  for either files or subdirectories whose names match a filename pattern.
563  Note that the order in which files are returned is completely undefined!
564 
565  @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
566  return files, directories, or both. If the ignoreHiddenFiles flag
567  is also added to this value, hidden files won't be returned
568  @param searchRecursively if true, all subdirectories will be recursed into to do
569  an exhaustive search
570  @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
571  @returns the set of files that were found
572 
573  @see getNumberOfChildFiles, DirectoryIterator
574  */
575  Array<File> findChildFiles (int whatToLookFor,
576  bool searchRecursively,
577  const String& wildCardPattern = "*") const;
578 
579  /** Searches inside a directory for files matching a wildcard pattern.
580  Note that there's a newer, better version of this method which returns the results
581  array, and in almost all cases, you should use that one instead! This one is kept around
582  mainly for legacy code to use.
583  */
584  int findChildFiles (Array<File>& results, int whatToLookFor,
585  bool searchRecursively, const String& wildCardPattern = "*") const;
586 
587  /** Searches inside a directory and counts how many files match a wildcard pattern.
588 
589  Assuming that this file is a directory, this method will search it
590  for either files or subdirectories whose names match a filename pattern,
591  and will return the number of matches found.
592 
593  This isn't a recursive call, and will only search this directory, not
594  its children.
595 
596  @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
597  count files, directories, or both. If the ignoreHiddenFiles flag
598  is also added to this value, hidden files won't be counted
599  @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
600  @returns the number of matches found
601  @see findChildFiles, DirectoryIterator
602  */
603  int getNumberOfChildFiles (int whatToLookFor,
604  const String& wildCardPattern = "*") const;
605 
606  /** Returns true if this file is a directory that contains one or more subdirectories.
607  @see isDirectory, findChildFiles
608  */
609  bool containsSubDirectories() const;
610 
611  //==============================================================================
612  /** Creates a stream to read from this file.
613 
614  Note that this is an old method, and actually it's usually best to avoid it and
615  instead use an RAII pattern with an FileInputStream directly, e.g.
616  @code
617  FileInputStream input (fileToOpen);
618 
619  if (input.openedOk())
620  {
621  input.read (etc...
622  }
623  @endcode
624 
625  @returns a stream that will read from this file (initially positioned at the
626  start of the file), or nullptr if the file can't be opened for some reason
627  @see createOutputStream, loadFileAsData
628  */
629  FileInputStream* createInputStream() const;
630 
631  /** Creates a stream to write to this file.
632 
633  Note that this is an old method, and actually it's usually best to avoid it and
634  instead use an RAII pattern with an FileOutputStream directly, e.g.
635  @code
636  FileOutputStream output (fileToOpen);
637 
638  if (output.openedOk())
639  {
640  output.read etc...
641  }
642  @endcode
643 
644  If the file exists, the stream that is returned will be positioned ready for
645  writing at the end of the file. If you want to write to the start of the file,
646  replacing the existing content, then you can do the following:
647  @code
648  FileOutputStream output (fileToOverwrite);
649 
650  if (output.openedOk())
651  {
652  output.setPosition (0);
653  output.truncate();
654  ...
655  }
656  @endcode
657 
658  @returns a stream that will write to this file (initially positioned at the
659  end of the file), or nullptr if the file can't be opened for some reason
660  @see createInputStream, appendData, appendText
661  */
662  FileOutputStream* createOutputStream (size_t bufferSize = 0x8000) const;
663 
664  //==============================================================================
665  /** Loads a file's contents into memory as a block of binary data.
666 
667  Of course, trying to load a very large file into memory will blow up, so
668  it's better to check first.
669 
670  @param result the data block to which the file's contents should be appended - note
671  that if the memory block might already contain some data, you
672  might want to clear it first
673  @returns true if the file could all be read into memory
674  */
675  bool loadFileAsData (MemoryBlock& result) const;
676 
677  /** Reads a file into memory as a string.
678 
679  Attempts to load the entire file as a zero-terminated string.
680 
681  This makes use of InputStream::readEntireStreamAsString, which can
682  read either UTF-16 or UTF-8 file formats.
683  */
684  String loadFileAsString() const;
685 
686  /** Reads the contents of this file as text and splits it into lines, which are
687  appended to the given StringArray.
688  */
689  void readLines (StringArray& destLines) const;
690 
691  //==============================================================================
692  /** Appends a block of binary data to the end of the file.
693 
694  This will try to write the given buffer to the end of the file.
695 
696  @returns false if it can't write to the file for some reason
697  */
698  bool appendData (const void* dataToAppend,
699  size_t numberOfBytes) const;
700 
701  /** Replaces this file's contents with a given block of data.
702 
703  This will delete the file and replace it with the given data.
704 
705  A nice feature of this method is that it's safe - instead of deleting
706  the file first and then re-writing it, it creates a new temporary file,
707  writes the data to that, and then moves the new file to replace the existing
708  file. This means that if the power gets pulled out or something crashes,
709  you're a lot less likely to end up with a corrupted or unfinished file..
710 
711  Returns true if the operation succeeds, or false if it fails.
712 
713  @see appendText
714  */
715  bool replaceWithData (const void* dataToWrite,
716  size_t numberOfBytes) const;
717 
718  /** Appends a string to the end of the file.
719 
720  This will try to append a text string to the file, as either 16-bit unicode
721  or 8-bit characters in the default system encoding.
722 
723  It can also write the 'ff fe' unicode header bytes before the text to indicate
724  the endianness of the file.
725 
726  If lineEndings is nullptr, then line endings in the text won't be modified. If you
727  pass "\\n" or "\\r\\n" then this function will replace any existing line feeds.
728 
729  @see replaceWithText
730  */
731  bool appendText (const String& textToAppend,
732  bool asUnicode = false,
733  bool writeUnicodeHeaderBytes = false,
734  const char* lineEndings = "\r\n") const;
735 
736  /** Replaces this file's contents with a given text string.
737 
738  This will delete the file and replace it with the given text.
739 
740  A nice feature of this method is that it's safe - instead of deleting
741  the file first and then re-writing it, it creates a new temporary file,
742  writes the text to that, and then moves the new file to replace the existing
743  file. This means that if the power gets pulled out or something crashes,
744  you're a lot less likely to end up with an empty file..
745 
746  For an explanation of the parameters here, see the appendText() method.
747 
748  Returns true if the operation succeeds, or false if it fails.
749 
750  @see appendText
751  */
752  bool replaceWithText (const String& textToWrite,
753  bool asUnicode = false,
754  bool writeUnicodeHeaderBytes = false,
755  const char* lineEndings = "\r\n") const;
756 
757  /** Attempts to scan the contents of this file and compare it to another file, returning
758  true if this is possible and they match byte-for-byte.
759  */
760  bool hasIdenticalContentTo (const File& other) const;
761 
762  //==============================================================================
763  /** Creates a set of files to represent each file root.
764 
765  e.g. on Windows this will create files for "c:\", "d:\" etc according
766  to which ones are available. On the Mac/Linux, this will probably
767  just add a single entry for "/".
768  */
769  static void findFileSystemRoots (Array<File>& results);
770 
771  /** Finds the name of the drive on which this file lives.
772  @returns the volume label of the drive, or an empty string if this isn't possible
773  */
774  String getVolumeLabel() const;
775 
776  /** Returns the serial number of the volume on which this file lives.
777  @returns the serial number, or zero if there's a problem doing this
778  */
779  int getVolumeSerialNumber() const;
780 
781  /** Returns the number of bytes free on the drive that this file lives on.
782 
783  @returns the number of bytes free, or 0 if there's a problem finding this out
784  @see getVolumeTotalSize
785  */
786  int64 getBytesFreeOnVolume() const;
787 
788  /** Returns the total size of the drive that contains this file.
789 
790  @returns the total number of bytes that the volume can hold
791  @see getBytesFreeOnVolume
792  */
793  int64 getVolumeTotalSize() const;
794 
795  /** Returns true if this file is on a CD or DVD drive. */
796  bool isOnCDRomDrive() const;
797 
798  /** Returns true if this file is on a hard disk.
799 
800  This will fail if it's a network drive, but will still be true for
801  removable hard-disks.
802  */
803  bool isOnHardDisk() const;
804 
805  /** Returns true if this file is on a removable disk drive.
806 
807  This might be a usb-drive, a CD-rom, or maybe a network drive.
808  */
809  bool isOnRemovableDrive() const;
810 
811  //==============================================================================
812  /** Launches the file as a process.
813 
814  - if the file is executable, this will run it.
815 
816  - if it's a document of some kind, it will launch the document with its
817  default viewer application.
818 
819  - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
820 
821  @see revealToUser
822  */
823  bool startAsProcess (const String& parameters = String()) const;
824 
825  /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
826  @see startAsProcess
827  */
828  void revealToUser() const;
829 
830  //==============================================================================
831  /** A set of types of location that can be passed to the getSpecialLocation() method.
832  */
834  {
835  /** The user's home folder. This is the same as using File ("~"). */
837 
838  /** The user's default documents folder. On Windows, this might be the user's
839  "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
840  doesn't tend to have one of these, so it might just return their home folder.
841  */
843 
844  /** The folder that contains the user's desktop objects. */
846 
847  /** The most likely place where a user might store their music files. */
849 
850  /** The most likely place where a user might store their movie files. */
852 
853  /** The most likely place where a user might store their picture files. */
855 
856  /** The folder in which applications store their persistent user-specific settings.
857  On Windows, this might be "\Documents and Settings\username\Application Data".
858  On the Mac, it might be "~/Library". If you're going to store your settings in here,
859  always create your own sub-folder to put them in, to avoid making a mess.
860  On GNU/Linux it is "~/.config".
861  */
863 
864  /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
865  of the computer, rather than just the current user.
866 
867  On the Mac it'll be "/Library", on Windows, it could be something like
868  "\Documents and Settings\All Users\Application Data".
869 
870  On GNU/Linux it is "/opt".
871 
872  Depending on the setup, this folder may be read-only.
873  */
875 
876  /** A place to put documents which are shared by all users of the machine.
877  On Windows this may be somewhere like "C:\Users\Public\Documents", on OSX it
878  will be something like "/Users/Shared". Other OSes may have no such concept
879  though, so be careful.
880  */
882 
883  /** The folder that should be used for temporary files.
884  Always delete them when you're finished, to keep the user's computer tidy!
885  */
887 
888  /** Returns this application's executable file.
889 
890  If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
891  host app.
892 
893  On the mac this will return the unix binary, not the package folder - see
894  currentApplicationFile for that.
895 
896  See also invokedExecutableFile, which is similar, but if the exe was launched from a
897  file link, invokedExecutableFile will return the name of the link.
898  */
900 
901  /** Returns this application's location.
902 
903  If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
904  host app.
905 
906  On the mac this will return the package folder (if it's in one), not the unix binary
907  that's inside it - compare with currentExecutableFile.
908  */
910 
911  /** Returns the file that was invoked to launch this executable.
912  This may differ from currentExecutableFile if the app was started from e.g. a link - this
913  will return the name of the link that was used, whereas currentExecutableFile will return
914  the actual location of the target executable.
915  */
917 
918  /** In a plugin, this will return the path of the host executable. */
920 
921  #if JUCE_WINDOWS || DOXYGEN
922  /** On a Windows machine, returns the location of the Windows/System32 folder. */
924  #endif
925 
926  /** The directory in which applications normally get installed.
927  So on windows, this would be something like "C:\Program Files", on the
928  Mac "/Applications", or "/usr" on linux.
929  */
931 
932  #if JUCE_WINDOWS || DOXYGEN
933  /** On a Windows machine, returns the directory in which 32 bit applications
934  normally get installed. On a 64 bit machine this would be something like
935  "C:\Program Files (x86)", whereas for 32 bit machines this would match
936  globalApplicationsDirectory and be something like "C:\Program Files".
937 
938  @see globalApplicationsDirectory
939  */
940  globalApplicationsDirectoryX86
941  #endif
942  };
943 
944  /** Finds the location of a special type of file or directory, such as a home folder or
945  documents folder.
946 
947  @see SpecialLocationType
948  */
949  static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
950 
951  //==============================================================================
952  /** Returns a temporary file in the system's temp directory.
953  This will try to return the name of a non-existent temp file.
954  To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
955  */
956  static File createTempFile (StringRef fileNameEnding);
957 
958  //==============================================================================
959  /** Returns the current working directory.
960  @see setAsCurrentWorkingDirectory
961  */
962  static File getCurrentWorkingDirectory();
963 
964  /** Sets the current working directory to be this file.
965 
966  For this to work the file must point to a valid directory.
967 
968  @returns true if the current directory has been changed.
969  @see getCurrentWorkingDirectory
970  */
971  bool setAsCurrentWorkingDirectory() const;
972 
973  //==============================================================================
974  /** The system-specific file separator character.
975  On Windows, this will be '\', on Mac/Linux, it'll be '/'
976  */
977  static juce_wchar getSeparatorChar();
978 
979  /** The system-specific file separator character, as a string.
980  On Windows, this will be '\', on Mac/Linux, it'll be '/'
981  */
982  static StringRef getSeparatorString();
983 
984  //==============================================================================
985  /** Returns a version of a filename with any illegal characters removed.
986 
987  This will return a copy of the given string after removing characters
988  that are not allowed in a legal filename, and possibly shortening the
989  string if it's too long.
990 
991  Because this will remove slashes, don't use it on an absolute pathname - use
992  createLegalPathName() for that.
993 
994  @see createLegalPathName
995  */
996  static String createLegalFileName (const String& fileNameToFix);
997 
998  /** Returns a version of a path with any illegal characters removed.
999 
1000  Similar to createLegalFileName(), but this won't remove slashes, so can
1001  be used on a complete pathname.
1002 
1003  @see createLegalFileName
1004  */
1005  static String createLegalPathName (const String& pathNameToFix);
1006 
1007  /** Indicates whether filenames are case-sensitive on the current operating system. */
1008  static bool areFileNamesCaseSensitive();
1009 
1010  /** Returns true if the string seems to be a fully-specified absolute path. */
1011  static bool isAbsolutePath (StringRef path);
1012 
1013  /** Creates a file that simply contains this string, without doing the sanity-checking
1014  that the normal constructors do.
1015 
1016  Best to avoid this unless you really know what you're doing.
1017  */
1018  static File createFileWithoutCheckingPath (const String& absolutePath) noexcept;
1019 
1020  /** Adds a separator character to the end of a path if it doesn't already have one. */
1021  static String addTrailingSeparator (const String& path);
1022 
1023  //==============================================================================
1024  /** Tries to create a symbolic link and returns a boolean to indicate success */
1025  bool createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const;
1026 
1027  /** Returns true if this file is a link or alias that can be followed using getLinkedTarget(). */
1028  bool isSymbolicLink() const;
1029 
1030  /** If this file is a link or alias, this returns the file that it points to.
1031  If the file isn't actually link, it'll just return itself.
1032  */
1033  File getLinkedTarget() const;
1034 
1035  /** Create a symbolic link to a native path and return a boolean to indicate success.
1036 
1037  Use this method if you want to create a link to a relative path or a special native
1038  file path (such as a device file on Windows).
1039  */
1040  static bool createSymbolicLink (const File& linkFileToCreate,
1041  const String& nativePathOfTarget,
1042  bool overwriteExisting);
1043 
1044  /** This returns the native path that the symbolic link points to. The returned path
1045  is a native path of the current OS and can be a relative, absolute or special path. */
1046  String getNativeLinkedTarget() const;
1047 
1048  #if JUCE_WINDOWS || DOXYGEN
1049  /** Windows ONLY - Creates a win32 .LNK shortcut file that links to this file. */
1050  bool createShortcut (const String& description, const File& linkFileToCreate) const;
1051 
1052  /** Windows ONLY - Returns true if this is a win32 .LNK file. */
1053  bool isShortcut() const;
1054  #else
1055 
1056  #endif
1057 
1058  //==============================================================================
1059  #if JUCE_MAC || JUCE_IOS || DOXYGEN
1060  /** OSX ONLY - Finds the OSType of a file from the its resources. */
1061  OSType getMacOSType() const;
1062 
1063  /** OSX ONLY - Returns true if this file is actually a bundle. */
1064  bool isBundle() const;
1065  #endif
1066 
1067  #if JUCE_MAC || DOXYGEN
1068  /** OSX ONLY - Adds this file to the OSX dock */
1069  void addToDock() const;
1070  #endif
1071 
1072  //==============================================================================
1073  /** Comparator for files */
1075  {
1076  NaturalFileComparator (bool shouldPutFoldersFirst) noexcept : foldersFirst (shouldPutFoldersFirst) {}
1077 
1078  int compareElements (const File& firstFile, const File& secondFile) const
1079  {
1080  if (foldersFirst && (firstFile.isDirectory() != secondFile.isDirectory()))
1081  return firstFile.isDirectory() ? -1 : 1;
1082 
1083  #if NAMES_ARE_CASE_SENSITIVE
1084  return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), true);
1085  #else
1086  return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), false);
1087  #endif
1088  }
1089 
1090  bool foldersFirst;
1091  };
1092 
1093  /* These static objects are deprecated because it's too easy to accidentally use them indirectly
1094  during a static constructor, which leads to very obscure order-of-initialisation bugs.
1095  Use File::getSeparatorChar() and File::getSeparatorString(), and instead of File::nonexistent,
1096  just use File() or {}.
1097  */
1098  JUCE_DEPRECATED_STATIC (static const juce_wchar separator;)
1099  JUCE_DEPRECATED_STATIC (static const StringRef separatorString;)
1100  JUCE_DEPRECATED_STATIC (static const File nonexistent;)
1101 
1102 private:
1103  //==============================================================================
1104  String fullPath;
1105 
1106  static String parseAbsolutePath (const String&);
1107  String getPathUpToLastSlash() const;
1108 
1109  Result createDirectoryInternal (const String&) const;
1110  bool copyInternal (const File&) const;
1111  bool moveInternal (const File&) const;
1112  bool replaceInternal (const File&) const;
1113  bool setFileTimesInternal (int64 m, int64 a, int64 c) const;
1114  void getFileTimesInternal (int64& m, int64& a, int64& c) const;
1115  bool setFileReadOnlyInternal (bool) const;
1116  bool setFileExecutableInternal (bool) const;
1117 };
1118 
1119 } // namespace juce
1120 
1121 /** @}*/
#define JUCE_API
This macro is added to all JUCE public class declarations.
The most likely place where a user might store their movie files.
Definition: juce_File.h:851
The user&#39;s default documents folder.
Definition: juce_File.h:842
A simple class for holding temporary references to a string literal or String.
An equivalent of the userApplicationDataDirectory folder that is shared by all users of the computer...
Definition: juce_File.h:874
In a plugin, this will return the path of the host executable.
Definition: juce_File.h:919
The user&#39;s home folder.
Definition: juce_File.h:836
int compareNatural(StringRef other, bool isCaseSensitive=false) const noexcept
Compares two strings, taking into account textual characteristics like numbers and spaces...
A place to put documents which are shared by all users of the machine.
Definition: juce_File.h:881
A special array for holding a list of strings.
The JUCE String class!
Definition: juce_String.h:42
Returns this application&#39;s executable file.
Definition: juce_File.h:899
Comparator for files.
Definition: juce_File.h:1074
The directory in which applications normally get installed.
Definition: juce_File.h:930
Represents the &#39;success&#39; or &#39;failure&#39; of an operation, and holds an associated error message to descr...
Definition: juce_Result.h:60
Represents a local file or directory.
Definition: juce_File.h:44
Holds a resizable array of primitive or copy-by-value objects.
Definition: juce_Array.h:59
An input stream that reads from a local file.
On a Windows machine, returns the location of the Windows/System32 folder.
Definition: juce_File.h:923
An output stream that writes into a local file.
The folder in which applications store their persistent user-specific settings.
Definition: juce_File.h:862
SpecialLocationType
A set of types of location that can be passed to the getSpecialLocation() method. ...
Definition: juce_File.h:833
TypesOfFileToFind
Used in file searching, to specify whether to return files, directories, or both. ...
Definition: juce_File.h:551
bool isDirectory() const
Checks whether the file is a directory that exists.
The folder that contains the user&#39;s desktop objects.
Definition: juce_File.h:845
The most likely place where a user might store their picture files.
Definition: juce_File.h:854
A class to hold a resizable block of raw data.
Holds an absolute date and time.
Definition: juce_Time.h:40
const String & getFullPathName() const noexcept
Returns the complete, absolute path of this file.
Definition: juce_File.h:153
Returns the file that was invoked to launch this executable.
Definition: juce_File.h:916
Returns this application&#39;s location.
Definition: juce_File.h:909
The folder that should be used for temporary files.
Definition: juce_File.h:886
The most likely place where a user might store their music files.
Definition: juce_File.h:848