- Ошибка «Fatal: destination path ‘.’ already exists and is not an empty directory»
- Благодарность автору
- How to clone git repo to the current directory
- Specify directory to clone to
- Clone to the current directory
- Error «fatal: destination path ‘.’ already exists and is not an empty directory»
- Как удалить файл из внешнего хранилища android studio, используя только URI
- 2 ответа
- Android Tutorial: Android External Storage
- 1 What is Android external storage?
- 2 Why external storage?
- 3 Android external storage APIs Overview
- 3.1 Environment.getExternalStorageDirectory()
- 3.2 Context.getExternalFilesDir(String type)
- 3.3 Context.getExternalCacheDir()
- 3.4 Environment.getExternalStoragePublicDirectory(String type)
- 4 How to Use Android external storage
- 5 Android external storage example
- 5.1 Add WRITE_EXTERNAL_STORAGE permission
- 5.2 Helper method to check external storage state
- 5.3 Helper method to write file
- 5.4 Listen button clicking
Ошибка «Fatal: destination path ‘.’ already exists and is not an empty directory»
Описание и решение ошибки «Fatal: destination path ‘.’ already exists and is not an empty directory» при выполнении команды git clone.
Давайте представим что мы хотим клонировать репозиторий с Git в текущую директорию проекта, делается это, путем указания точки в конце команды. В директории могут находится скрытые файлы и папки. Например .idea от phpStorm. В этом случае, мы получим ошибку:
В таком случае, нужно будет полностью очистить директорию, куда вы клонируете репозиторий, а это приведет к определенным проблемам. Например если удалить директорию .idea , то мы удалим все настройки проекта в phpStorm.
Для того, чтобы избежать подобного рода проблем, находясь в нужной директории, можно воспользоваться следующим набором команд:
Описание того, что мы делаем:
- Инициализируем пустой репозиторий в директории.
- Добавляем удаленный репозиторий (вместо , укажите путь до репозитория).
- Выбираем ветку с которой хотим работать.
В итоге Git сам обновит тот новосозданный нами репозиторий, в соответствии с удаленным, который мы указали во второй команде. Ну, а последней командой, мы просто укажем Git с какой веткой хотим работать и он подтянет версию проекта из этой ветки.
Вот такое альтернативное решение клонирования репозитория в текущую директорию, даже если она не пуста.
Благодарность автору
Если по какой-либо причине вы хотите поблагодарить автора данного ресурса, вы можете это сделать одним из удобных для вас способов ниже.
Один из самых популярных способов поблагодарить автора, воспользоваться сервисом Яндекс.Деньги.
Источник
How to clone git repo to the current directory
The most common way to clone git repository is to enter in the terminal command that looks like something like this:
This command will create the directory «my_project» in the current directory and it will clone repo to that directory. Here is an example:
Command «pwd» prints the directory where you are now. The command «git clone . » does the clone. And with «ls» command we check that there is a hidden «.git» directory that stores all the history and other meta information and there is a «README.md» file.
Specify directory to clone to
Sometimes you need to place git repository in some other directory. Here is an example:
As you can see here I used «git clone» command with two parameters:
- the first paramter is the url to the repo
- the second paramter is the directory where to clone repo
Clone to the current directory
And sometimes you need to clone the git repo to the current directory. To specify the current directory the symbol dot is used. So to clone repo to the current directory you need to specify two parameters to git clone:
- the url of the repo
- just one symbol — dot — «.» — it means current directory
Here is an example:
Here I have created a new directory with the name «the_project», then I’ve entered it with «cd» command and did the clone with the command «git clone url .». The dot in this command is what makes git clone to the directory where I’m now.
Error «fatal: destination path ‘.’ already exists and is not an empty directory»
Sometimes you can see error message:
It means exactly what it it written in this message. You are trying to checkout repo to the directory that has some files in it. With the command «ls» you can check what files are in the current directory. It is also possible that there are some hidden files, so it is better to use «-a» option to make «ls» show all files including hidden:
Источник
Как удалить файл из внешнего хранилища android studio, используя только URI
Я просмотрел примеры других людей и реализовал это.
Теперь единственная проблема заключается в том, что имя пути, которое я получаю, это «content: // downloads / all_downloads / 644», и, согласно моему распечатанному logcat, этот файл не может быть найден. Примечание. Этот файл действительно существует, и я использовал тот же uri для воспроизведения видео. Спасибо за помощь. РЕДАКТИРОВАТЬ: ОК. Вот как я получил свой URI.
Я очень признателен за приведенные ниже предложения, но я все еще застрял даже после прочтения документации. Предположим, я не могу удалить с помощью URI, есть ли способ вместо этого преобразовать мой URI во что-то полезное. Я не хочу вручную вводить адрес расположения моих файлов.
@ Вот мой весь код .
Public class Cacher <
2 ответа
Итак, вот решение моей проблемы для тех, кто не хочет читать наши комментарии. Сначала выберите каталог для загрузки. Затем используйте этот путь к файлам и используйте функцию delete (). Имейте в виду, что после создания каталога с именем папки вам нужно будет ссылаться только на имя папки, а не на весь путь. Вот код, который, я надеюсь, поможет:
// Где я создаю каталог
Я просмотрел примеры других людей и реализовал это.
Это будет работать только в том случае, если Uri имеет схему file и у вас есть права на запись в каталог, содержащий файл.
Как удалить файл из внешнего хранилища android studio, используя только URI
Скорее всего, нет.
Если вы получаете Uri от ACTION_OPEN_DOCUMENT или ACTION_CREATE_DOCUMENT , оберните Uri в DocumentFile , используя fromSingleUri() , затем вызовите delete() на DocumentFile .
Для любого другого content Uri вы можете попробовать вызвать delete() на ContentResolver , но не ожидайте, что это сработает. Не требуется, чтобы ContentProvider предлагал вам какой-либо способ удаления части контента. Приложение, поставляющее ContentProvider , должно иметь собственный способ разрешать пользователям удалять вещи.
Источник
Android Tutorial: Android External Storage
Tutorial about how to use Android external storage.
1 What is Android external storage?
What Android «external storage» means is described in Android SDK Document:
Every Android-compatible device supports a shared «external storage» that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
So don’t be confused by the word «external» here. External storage can better be thought as media or shared storage. Traditionally this is an removable SD (Secure Digital) card, but it may also be implemented as built-in non-removable storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
2 Why external storage?
Android has already provided efficient internal storage for application, but still there is much need for external storage under certain circumstance.
- Need more memory or disk space to save big files;
- Let data saved or generated in your application be accessed by other applications;
- Some saved data should not be deleted although your application is uninstalled. For example, pictures, videos downloaded by your application.
3 Android external storage APIs Overview
Main APIs for Android external storage.
- Environment.getExternalStorageDirectory() : return the primary external storage root directory.
- Context.getExternalFilesDir(String type) : return the absolute path of the directory on the primary external storage where the application can place its own files.
- Context.getExternalCacheDir() | return reference to your application specific path of cache directory on external storage.
- Environment.getExternalStoragePublicDirectory(String type) | return public external storage directory for saving files of a particular type.
Following figure gives an overview of Android external storage APIs.
3.1 Environment.getExternalStorageDirectory()
Environment.getExternalStorageDirectory() returns top-level directory of the primary external storage.
If device has multiple external storage directories, returned directory represents the primary external storage that the user will interact with. There is also APIs available for accessing secondary storage or getting external storage directories list.
- Context.getExternalFilesDirs(String type)
- Context.getExternalCacheDirs()
- Context.getExternalMediaDirs()
It is noticed that the returned directory of Environment.getExternalStorageDirectory() is the top-level directory of the external storage. You application should avoid placing files directly under this top-level directory. If your application needs save public or shared data, you’d better use directory returned by getExternalStoragePublicDirectory(String type) ; on the other hand, if your application only needs to store its own internal data on external storage, you’d better consider using getExternalFilesDir(String) or getExternalCacheDir() instead.
3.2 Context.getExternalFilesDir(String type)
Returns the absolute path to the directory on the primary shared or external storage device where the application can place persistent files it owns. These files are internal to the application.
The returned directory is owned by the application and its contents will be deleted when the application is uninstalled.
The type parameter can be null or one of the following constant value.
- Environment.DIRECTORY_MUSIC
- Environment.DIRECTORY_PODCASTS
- Environment.DIRECTORY_RINGTONES
- Environment.DIRECTORY_ALARMS
- Environment.DIRECTORY_NOTIFICATIONS
- Environment.DIRECTORY_PICTURES
- Environment.DIRECTORY_MOVIES
If the type parameter is null , the returned path will be the root the files directory; otherwise, will be a sub directory of the given type.
3.3 Context.getExternalCacheDir()
Returns absolute path to application-specific directory on the primary shared or external storage device where the application can place cache files it owns.
Cached files under returned directory will be deleted when the application is uninstalled. Android platform does not always monitor the space available in shared storage, and thus may not automatically delete these cached files. Your application itself should always manage the maximum space used in this location.
3.4 Environment.getExternalStoragePublicDirectory(String type)
Get a top-level shared or external storage directory for placing files of a particular type.
The type parameter CAN NOT be null , should be one of the following constant value.
- Environment.DIRECTORY_MUSIC
- Environment.DIRECTORY_PODCASTS
- Environment.DIRECTORY_RINGTONES
- Environment.DIRECTORY_ALARMS
- Environment.DIRECTORY_NOTIFICATIONS
- Environment.DIRECTORY_PICTURES
- Environment.DIRECTORY_MOVIES
Because this returned directory is public and is for shared files, you application should be careful and avoid erasing any files here.
4 How to Use Android external storage
External storage of Android device may not always be available, for example:
- external storage may not be accessible if it has been mounted by users on their computer;
- external storage has been removed from device.
So the first step is to check state of the external storage. External storage state can be checked using Environment.getExternalStorageState(File path) . More details can refer to Android Tutorial: Check SD Card Status.
The second step is to add android.permission.READ_EXTERNAL_STORAGE or android.permission.WRITE_EXTERNAL_STORAGE permission to your application.
Note: From Android 6.0+, application has to ask user for a permission one-by-one at runtime instead of being granted any permission at installation time.
The third step is to get File object reference of external storage directory.
Lastly, write or read data using common java.io APIs with the directory File object.
5 Android external storage example
There are two main features in this simple demo:
- Show various external storage full path using Toast ;
- Try to write demo file to external storage;
Main UI of the demo looks like screenshot below.
5.1 Add WRITE_EXTERNAL_STORAGE permission
Add android.permission.WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file of your Android application project.
5.2 Helper method to check external storage state
Create a helper method in Activity class to check external storage state.
5.3 Helper method to write file
Create a common helper method to write string to a file.
5.4 Listen button clicking
Lastly, implement View.OnClickListener interface in the demo Activity.
You can check the saved file via file explore of Android Device Monitor (DDMS) in Android Studio or Eclipse.
Источник