Java Code Examples for java.io.File.canWrite()

The following are Jave code examples for showing how to use canWrite() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Kids-Portal-Android   File: Activity_settings_data.java   View Source Code Vote up 6 votes
private void restore_ReadLater () {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + "jae.KidsPortal.Browser"
                    + "//databases//" + "readLater_DB_v01.db";
            String backupDBPath = "//Android//" + "//data//" + "//browser.backup//" + "readLater_DB_v01.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(backupDB).getChannel();
            FileChannel dst = new FileOutputStream(currentDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();

            Snackbar.make(frameLayout, getString(R.string.toast_restore), Snackbar.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Snackbar.make(frameLayout, getString(R.string.toast_restore_not), Snackbar.LENGTH_LONG).show();
    }
}
 
Example 2
Project: MyCourses   File: DosyaOkumaOrnegiSade.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws FileNotFoundException {
    File ogrencilerDosya = new File(".\\config\\Ogrenciler.txt"); 
    // Mac: "./config/Ogrenciler.txt"
    
    if(!ogrencilerDosya.exists() || !ogrencilerDosya.canRead()
            || !ogrencilerDosya.isFile() ) {
        System.out.println("Dosya yok ya da okuma hakkı yok." 
                + ogrencilerDosya.getAbsolutePath() );
        return;
    }
    
    Scanner dosyaOkuyucu = new Scanner(ogrencilerDosya);

    File ciktiDosyasi = new File(".\\config\\Ogrenciler_cikti.txt"); 
    // Mac: "./config/Ogrenciler_cikti.txt"
    
    if (!ciktiDosyasi.canWrite()) {
        System.out.println("Yazma hakki yok");
        return;
    }
    
    PrintWriter dosyaYazici = new PrintWriter(ciktiDosyasi);

    // Dosyaya ek yapmak icin:
    // FileOutputStream fos = new FileOutputStream(ciktiDosyasi);
    // PrintWriter dosyaYazici2 = new PrintWriter(fos, true);
    for (int i = 0; dosyaOkuyucu.hasNextLine(); i++) {
        String mevcutSatir = dosyaOkuyucu.nextLine();
        System.out.println(mevcutSatir);
        dosyaYazici.println("Satir " + (i + 1) + ": " + mevcutSatir);
    }

    dosyaYazici.close();
    dosyaOkuyucu.close();
}
 
Example 3
Project: AspriseOCR   File: Util.java   View Source Code Vote up 6 votes
public static FileOutputStream openOutputStream(File file) throws IOException
{
	if (file.exists())
	{
		if (file.isDirectory())
		{
			throw new IOException("File '" + file + "' exists but is a directory");
		}
		if (file.canWrite() == false)
		{
			throw new IOException("File '" + file + "' cannot be written to");
		}
	}
	else
	{
		File parent = file.getParentFile();
		if (parent != null && parent.exists() == false)
		{
			if (parent.mkdirs() == false)
			{
				throw new IOException("File '" + file + "' could not be created");
			}
		}
	}
	return new FileOutputStream(file);
}
 
Example 4
Project: simple-share-android   File: FileUtils.java   View Source Code Vote up 6 votes
public static boolean deleteFile(File file) {
    if (file.exists() && file.isFile() && file.canWrite()) {
        return file.delete();
    } else if (file.isDirectory()) {
        if (null != file && file.list() != null && file.list().length == 0) {
            return file.delete();
        } else {
            String[] fileList = file.list();
            for (String filePaths : fileList) {
                File tempFile = new File(file.getAbsolutePath() + "/" + filePaths);
                if (tempFile.isFile()) {
                    tempFile.delete();
                } else {
                    deleteFile(tempFile);
                    tempFile.delete();
                }
            }

        }
        if (file.exists()) {
            return file.delete();
        }
    }
    return false;
}
 
Example 5
Project: flume-release-1.7.0   File: LogUtils.java   View Source Code Vote up 6 votes
/**
 * Find all log files within a directory
 *
 * @param logDir directory to search
 * @return List of data files within logDir
 */
static List<File> getLogs(File logDir) {
  List<File> result = Lists.newArrayList();
  File[] files = logDir.listFiles();
  if (files == null) {
    String msg = logDir + ".listFiles() returned null: ";
    msg += "File = " + logDir.isFile() + ", ";
    msg += "Exists = " + logDir.exists() + ", ";
    msg += "Writable = " + logDir.canWrite();
    throw new IllegalStateException(msg);
  }
  for (File file : files) {
    String name = file.getName();
    if (pattern.matcher(name).matches()) {
      result.add(file);
    }
  }
  return result;
}
 
Example 6
Project: neoscada   File: FileNamePage.java   View Source Code Vote up 6 votes
private void validate () throws Exception
{
    final String fileName = this.fileName.getText ();

    if ( fileName.length () == 0 )
    {
        throw new IllegalStateException ( Messages.FileNamePage_State_NotFileSelected );
    }

    final File file = new File ( fileName );

    if ( file.exists () && !file.isFile () )
    {
        throw new IllegalArgumentException ( String.format ( Messages.FileNamePage_State_FileNoFile, fileName ) );
    }
    if ( !file.canWrite () && file.exists () )
    {
        throw new IllegalArgumentException ( String.format ( Messages.FileNamePage_State_FileCantWrite, fileName ) );
    }
}
 
Example 7
Project: camunda-bpm-swagger   File: AbstractModel.java   View Source Code Vote up 5 votes
@SneakyThrows
public void write(final File destination) {
  if (destination == null || !destination.canWrite() || !destination.exists() || !destination.isDirectory()) {
    throw new IllegalStateException("Cannot write to " + destination);
  }
  getCodeModel().build(destination);
}
 
Example 8
Project: memory   File: AllocateDirectMap.java   View Source Code Vote up 5 votes
static final boolean isFileReadOnly(final File file) {
  if (System.getProperty("os.name").startsWith("Windows")) {
    return !file.canWrite();
  }
  //All Unix-like OSes
  final Path path = Paths.get(file.getAbsolutePath());
  PosixFileAttributes attributes = null;
  try {
    attributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes();
  } catch (final IOException e) {
    // File presence is guaranteed. Ignore
    e.printStackTrace();
  }
  if (attributes == null) { return false; }

  // A file is read-only in Linux-derived OSes only when it has 0444 permissions.
  final Set<PosixFilePermission> permissions = attributes.permissions();
  int bits = 0;
  bits |= ((permissions.contains(PosixFilePermission.OWNER_READ))     ? 1 << 8 : 0);
  bits |= ((permissions.contains(PosixFilePermission.OWNER_WRITE))    ? 1 << 7 : 0);
  bits |= ((permissions.contains(PosixFilePermission.OWNER_EXECUTE))  ? 1 << 6 : 0);
  bits |= ((permissions.contains(PosixFilePermission.GROUP_READ))     ? 1 << 5 : 0);
  bits |= ((permissions.contains(PosixFilePermission.GROUP_WRITE))    ? 1 << 4 : 0);
  bits |= ((permissions.contains(PosixFilePermission.GROUP_EXECUTE))  ? 1 << 3 : 0);
  bits |= ((permissions.contains(PosixFilePermission.OTHERS_READ))    ? 1 << 2 : 0);
  bits |= ((permissions.contains(PosixFilePermission.OTHERS_WRITE))   ? 1 << 1 : 0);
  bits |= ((permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) ? 1      : 0);
  //System.out.println(Util.zeroPad(Integer.toBinaryString(bits), 32));
  //System.out.println(Util.zeroPad(Integer.toOctalString(bits), 4));
  // Here we are going to ignore the Owner Write & Execute bits to allow root/owner testing.
  return ((bits & 0477) == 0444);
}
 
Example 9
Project: usb-with-serial-port   File: SerialPort.java   View Source Code Vote up 5 votes
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
	/* Check access permission */
	if (!device.canRead() || !device.canWrite()) {
		try {
               /* Missing read/write permission, trying to chmod the file */
			Process su;
			su = Runtime.getRuntime().exec("/system/bin/su");
			String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
			su.getOutputStream().write(cmd.getBytes());
			if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
				throw new SecurityException();
			}
			Log.d(TAG,"target device missing read/write permission, trying to chmod the file");
		} catch (Exception e) {
			e.printStackTrace();
			throw new SecurityException();
		}
	}
	mFd = open(device.getAbsolutePath(), baudrate, flags);
	if (mFd == null) {
		Log.e(TAG, "native open returns null");
		throw new IOException();
	}
	path=device.getPath();
	mFileInputStream = new FileInputStream(mFd);
	mFileOutputStream = new FileOutputStream(mFd);
}
 
Example 10
Project: ide-plugins   File: ConfigureGluonProjectPage.java   View Source Code Vote up 5 votes
private boolean canCreate(File file) {
	while (!file.exists()) {
		file = file.getParentFile();
		if (file == null) {
			return false;
		}
	}
	return file.canWrite();
}
 
Example 11
Project: JRF   File: UnitTesting.java   View Source Code Vote up 5 votes
public static void compareFileAttributes(File f1, MsgFileInfos f2) {
	if (!f1.getName().equals(f2.getName()))
		fail("name");
	if (f1.canRead() != f2.canRead() || f1.canWrite() != f2.canWrite() || f1.canExecute() != f2.canExecute())
		fail("attributes");
	if (f1.length() != f2.length())
		fail("length");
	if (f1.lastModified() != f2.lastModified())
		fail("time");
	if (f1.isFile() != f2.isFile() || f1.isDirectory() != f2.isDirectory())
		fail("status");
}
 
Example 12
Project: jdk8u-jdk   File: Utils.java   View Source Code Vote up 5 votes
static void copyFile(File src, File dst) throws IOException {
    Path parent = dst.toPath().getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }
    Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
    if (dst.isDirectory() && !dst.canWrite()) {
        dst.setWritable(true);
    }
}
 
Example 13
Project: n4js   File: ShippedCodeAccess.java   View Source Code Vote up 5 votes
private static File getTempFolder() {
	final String tempFolder = StandardSystemProperty.JAVA_IO_TMPDIR.value();
	final File file = new File(tempFolder);
	if (!file.exists() || !file.canWrite()) {
		throw new RuntimeException("Cannot access temporary directory under: " + tempFolder);
	}
	return file;
}
 
Example 14
Project: FriendBook   File: FileUtil.java   View Source Code Vote up 5 votes
/**
 * 删除空目录
 * <p/>
 * 返回 0代表成功 ,1 代表没有删除权限, 2代表不是空目录,3 代表未知错误
 *
 * @return
 */
public static int deleteBlankPath(String path) {
    File f = new File(path);
    if (!f.canWrite()) {
        return 1;
    }
    if (f.list() != null && f.list().length > 0) {
        return 2;
    }
    if (f.delete()) {
        return 0;
    }
    return 3;
}
 
Example 15
Project: Notebook   File: FileUtils.java   View Source Code Vote up 5 votes
public static int deleteBlankPath(String path) {
	File f = new File(path);
	if (!f.canWrite()) {
		return 1;
	}
	if (f.list() != null && f.list().length > 0) {
		return 2;
	}
	if (f.delete()) {
		return 0;
	}
	return 3;
}
 
Example 16
Project: JRF   File: FileInfos.java   View Source Code Vote up 5 votes
public FileInfos(File f) {
	name = f.getName();
	if (name.isEmpty()) // Happens when 'f' is a root
		name = f.getPath();
	length = f.length();
	lastModified = f.lastModified();
	attributes = 0;
	if (f.isDirectory()) attributes |= BIT_ISDIRECTORY;
	if (f.isFile())      attributes |= BIT_ISFILE;
	if (f.isHidden())    attributes |= BIT_ISHIDDEN;
	if (f.canRead())     attributes |= BIT_CANREAD;
	if (f.canWrite())    attributes |= BIT_CANWRITE;
	if (f.canExecute())  attributes |= BIT_CANEXECUTE;
}
 
Example 17
Project: Android-SerialPort-API   File: SerialPort.java   View Source Code Vote up 5 votes
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {

		/* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
                su = Runtime.getRuntime().exec(sSuPath);
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }
        }

        mFd = open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }
 
Example 18
Project: javaide   File: FileUtils.java   View Source Code Vote up 4 votes
public static boolean canEdit(File file) {
    return file.canWrite() && com.duy.ide.file.FileUtils.hasExtension(file, ".java", ".xml", ".txt");
}
 
Example 19
Project: s-store   File: TarGenerator.java   View Source Code Vote up 4 votes
/**
 * Compression is determined directly by the suffix of the file name in
 * the specified path.
 *
 * @param inFile  Absolute or relative (from user.dir) File for
 *                     tar file to be created.  getName() Suffix must
 *                     indicate tar file and may indicate a compression
 *                     method.
 * @param overWrite    True to replace an existing file of same path.
 * @param blocksPerRecord  Null will use default tar value.
 */
public TarGenerator(File inFile, boolean overWrite,
                    Integer blocksPerRecord) throws IOException {

    File archiveFile = inFile.getAbsoluteFile();

    // Do this so we can be sure .getParent*() is non-null.  (Also allows
    // us to use .getPath() instead of very long .getAbsolutePath() for
    // error messages.
    int compression = TarFileOutputStream.Compression.NO_COMPRESSION;

    if (archiveFile.getName().endsWith(".tgz")
            || archiveFile.getName().endsWith(".tar.gz")) {
        compression = TarFileOutputStream.Compression.GZIP_COMPRESSION;
    } else if (archiveFile.getName().endsWith(".tar")) {

        // purposefully do nothing
    } else {
        throw new IllegalArgumentException(
            RB.singleton.getString(
                RB.UNSUPPORTED_EXT, getClass().getName(),
                archiveFile.getPath()));
    }

    if (archiveFile.exists()) {
        if (!overWrite) {
            throw new IOException(RB.singleton.getString(RB.DEST_EXISTS,
                    archiveFile.getPath()));
        }
    } else {
        File parentDir = archiveFile.getParentFile();

        // parentDir will be absolute, since archiveFile is absolute.
        if (parentDir.exists()) {
            if (!parentDir.isDirectory()) {
                throw new IOException(
                    RB.singleton.getString(
                        RB.PARENT_NOT_DIR, parentDir.getPath()));
            }

            if (!parentDir.canWrite()) {
                throw new IOException(
                    RB.singleton.getString(
                        RB.CANT_WRITE_PARENT, parentDir.getPath()));
            }
        } else {
            if (!parentDir.mkdirs()) {
                throw new IOException(
                    RB.singleton.getString(
                        RB.PARENT_CREATE_FAIL, parentDir.getPath()));
            }
        }
    }

    archive = (blocksPerRecord == null)
              ? new TarFileOutputStream(archiveFile, compression)
              : new TarFileOutputStream(archiveFile, compression,
                                        blocksPerRecord.intValue());

    if (blocksPerRecord != null && TarFileOutputStream.debug) {
        System.out.println(RB.singleton.getString(RB.BPR_WRITE,
                blocksPerRecord.intValue()));
    }
}
 
Example 20
Project: SimpleMarkdown   File: ExplorerActivity.java   View Source Code Vote up 4 votes
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_explorer);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Intent intent = getIntent();
        if (intent == null || !intent.hasExtra(MainActivity.EXTRA_REQUEST_CODE)) {
            finish();
            return;
        }

        docsDirPath = Utils.getDocsPath(this);

        requestCode = intent.getIntExtra(MainActivity.EXTRA_REQUEST_CODE, -1);
        switch (requestCode) {
            case MainActivity.OPEN_FILE_REQUEST:
                break;
            case MainActivity.SAVE_FILE_REQUEST:
                isSave = true;
                fileName = findViewById(R.id.file_name);
                fileName.setVisibility(View.VISIBLE);
                if (intent.hasExtra(MainActivity.EXTRA_FILE)) {
                    File file = (File) intent.getSerializableExtra(MainActivity.EXTRA_FILE);
                    if (file.exists() && file.canWrite()) {
                        docsDirPath = file.getParentFile().getAbsolutePath();
                        fileName.setText(file.getName());
                    } else {
                        fileName.setText("Untitled.md");
                    }
                }
                saveButton = findViewById(R.id.button_save);
                saveButton.setVisibility(View.VISIBLE);
                saveButton.setOnClickListener((v) -> {
                    Intent fileIntent = new Intent();
                    String absolutePath = String.format(
                            Locale.ENGLISH,
                            "%s/%s",
                            filePath,
                            fileName.getText().toString()
                    );
                    fileIntent.putExtra(MainActivity.EXTRA_FILE_PATH, absolutePath);
                    setResult(RESULT_OK, fileIntent);
                    finish();
                });
                break;
            default:
                finish();
                return;
        }
//        FloatingActionButton fab = findViewById(R.id.fab);
//        fab.setOnClickListener(view ->
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null)
//                        .show()
//        );

        listView = findViewById(R.id.file_list);
        File docsDir = new File(docsDirPath);
        if (!docsDir.exists()) {
            docsDir = Environment.getExternalStorageDirectory();
        }
        updateListView(docsDir);
    }