Create file in java android

Java Create File Examples

If you want to create a file in java. You have three ways to do that. This article will show you how to use java.io.File.createNewFile() , java.nio.file.Files and org.apache.commons.io.FileUtils.write() to create a file in java.

1. Use java.io.File.createNewFile().

This is the commonly used method, you should note the below tips.

  1. Create a java.io.File object with the file name. It can be a file name only like «abc.txt» , or an absolute path like «c:/WorkSpace/test/abc.txt» , or a relative path like «test1/test2/abc.txt» .
  2. Call the object’s createNewFile() method to create an empty file.
  3. The method returns true if the file is created successfully, and false if the file already exists.
  4. If the subdirectory in the path does not exist, it will throw java.io.IOException . So you had to make sure all the subfolder in the file path exists or has been created.
New file location is CI\WorkSpace\dev2qa.com\Code\dev2qa.com.txt File exist. New file location is C:\WorkSpace\dev2qa.com\Code\test\dev2qa.com.txt java.io.IOExcegtion: System can not find the path specified. at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaI0(CreateNewFile.java:63) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaIOExample(CreateNewFile.java:39) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:1?) New file location is C:\WorkSpace\dev2qa.com\Code\testRelative\dev2qa.com.txt java.io.IOExcegtion: System can not find the path. at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaI0(CreateNewFile.java:63) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaIOExamplefgfeateflgyjile.java:43) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:1?)
/* Use java.io.File.createNewFile(). */ public void createFileUseJavaIO(String filePath) < try < /* First check filePath variable value. */ if(filePath!=null && filePath.trim().length()>0) < File fileObj = new File(filePath); String absoluteFilePath = fileObj.getAbsolutePath(); System.out.println("NewFile location is " + absoluteFilePath); /* If not exist. */ if(!fileObj.exists()) < boolean result = fileObj.createNewFile(); if(result) < System.out.println("File " + filePath + " create success. "); >>else < System.out.println("File exist. "); >> > catch (IOException ex) < ex.printStackTrace(); >> /* Test createFileUseJavaIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * */ public void createFileUseJavaIOExample() < /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseJavaIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build a absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaIO(relativeFilePath); >

2. Use java.nio.file.Files.

  1. The code is more simple than java.io.
  2. If the subdirectory in the file path does not exist, it will throw java.nio.file.NoSuchFileException . So like java.io, you should first create the subfolder then create the new file.
java.nio.file.NoSuchFileExcegtion: testRelative\dev2qa.com.txt at sun.nio.fs.WindowsException.trans1ateToIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source) at java.nio.file.Files.newByteChannel(Unknown Source) at java.nio.file.Files.createFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUseJavaNewI0(§§e§teNewFile.java:113) at com.dev2qa.java.basic.file.CreateNewFile.createFileUseJavaNewIOExample(CreateHe§File.java:1B§) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:19)
/* Use java.nio.file.Files to creat. */ public void createFileUseJavaNewIO(String filePath) < try < /* First create the Path object. */ Path filePathObj = Paths.get(filePath); Path result = Files.createFile(filePathObj); System.out.println("Create " + filePath + " success. "); /* Show absolute path to see different filePath case real file location.*/ String fileAbsoultePath = result.toFile().getAbsolutePath(); System.out.println("File absolute path is " + fileAbsoultePath); >catch(Exception ex) < ex.printStackTrace(); >> /* Test createFileUseJavaNewIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * case1 and case3 will create the file under project root folder or current java class run folder. * */ public void createFileUseJavaNewIOExample() < /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseJavaNewIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build a absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaNewIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaNewIO(relativeFilePath); >

3. Use Apache Commons IO (org.apache.commons.io.FileUtils.write()).

  1. You should download and add Apache Commons IO jar into your java project. You can read Java Copy Directory Examples for more detail.
  2. Apache Commons IO will create the none exist subfolder automatically when it creates the file. No exception will be thrown.
  3. Below is the java code example.

/* Use Apache commons io to create new file. */ public void createFileUseApacheCommonsIO(String filePath) < try < File fileObj = new File(filePath); /* Call FileUtils.write to create the file and write some data in it. */ FileUtils.write(fileObj, "hello dev2qa.com"); System.out.println("Create " + filePath + " success. "); String fileAbsoultePath = fileObj.getAbsolutePath(); System.out.println("File absolute path is " + fileAbsoultePath); >catch(Exception ex) < ex.printStackTrace(); >> /* Test createFileUseApacheCommonsIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * case1 and case3 will create the file under project root folder or current java class run folder. * */ public void createFileUseApacheCommonsIOExample() < /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build an absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(relativeFilePath); >

4. Java Main Method.

  1. Below is the java main method of this example, it will invoke all the above methods to demo how to create a file in java source code programmatically.
public static void main(String[] args) < CreateNewFile cnf = new CreateNewFile(); //cnf.createFileUseJavaIOExample(); //cnf.createFileUseJavaNewIOExample(); cnf.createFileUseApacheCommonsIOExample(); >

Источник

Creating a Text File in Android Studio using Java

Evaluate the functionality of your file by recording the outcomes of a few assertions and share them with us. As an alternative, you can attempt the following approach: implement a method for storing data on disk and another method for retrieving it. Then, you can test your file by verifying that it works correctly. One thing to keep in mind is to confirm that the «filename» you are using is not a directory.

Android create text file on install

The onCreate file will be generated by this code consistently.

The creation of an instance of a File object does not result in file creation. This object represents a potential file on the filesystem and does not actually create the file. To create the file, use a FileOutputStream along with a background thread to write to it. The existence of the file can be checked by calling exists() on memoryFile .

It’s important to mention that getApplicationContext() is unnecessary in this context. Simply utilize getFilesDir() instead.

Android Save and Write Text File with Intent, getting IOException «No, data is an Intent? . You are assigning it to a variable named uri , confusing both of us. Now, uri will be a Uri? . You can use that with your

Create Text file in Android Studio Tutorial

In this video i will teach you how to create a text file in android studio using java. If you like
Duration: 6:38

Input Text and Save to Text file

This tutorial is about how to input text from user using EditText, validate it, and save it to text Duration: 21:00

Writing to Files in Internal Storage

Learn how to write to internal storage and create files in your Android app.Subscribe to IJ
Duration: 3:32

Read and Write text file from my own class in Android Studio

Instead of using OutputStreamWriter , FileOutputStream can be used to achieve the desired outcome.

 //what you had before FileOutputStream fos = null; try < fos = context.openFileOutput(filename, Context.MODE_PRIVATE); >catch (FileNotFoundException e) < e.printStackTrace(); >//use just the file output stream to write the data //data here is a String if (fos != null) < try < fos.write(data.getBytes()); fos.close(); >catch (IOException e) < e.printStackTrace(); >> 

Method to save data on disk :

protected static void saveDataOnDisk(String data) < ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try < ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream); objectOutput.writeObject(data); byte[] buffer = byteArrayOutputStream.toByteArray(); File loginDataFile = (new File(filePath)); // file path where you want to write your data loginDataFile.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile); fileOutputStream.write(buffer); fileOutputStream.close(); objectOutput.flush(); objectOutput.close(); byteArrayOutputStream.flush(); byteArrayOutputStream.close(); Log.i(“SAVE”, ”———————-DONE SAVING”); >catch(IOException ioe) < Log.i(“SAVE”, “———serializeObject|”+ioe); >> 

Method to fetch data from disk:

private static Object getDataFromDisk() < try < FileInputStream fileInputeStream = new FileInputStream(FilePath); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream); Object data = (Object) objectInputStream.readObject(); objectInputStream.close(); fileInputeStream.close(); return dataModel; >catch (Exception error) < Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error); >return null; > 

Read/Write String from/to a File in Android, writeTextToFile(getExternalFilesDir(«/»).getAbsolutePath() + «/output.txt», «my-example-text»);. After that, check the file at Android/data/

Cannot Find and Read Text File on Android Studio (Java)

ArrayList a = new ArrayList<>(); File file = new File(filename); StringBuilder text = new StringBuilder(); try < BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) < a.add(myReader.nextLine()); >br.close(); > catch (IOException e) < // OR CATCH AT LEAST EXCEPTION IF IT DOESNT WORK FOR FILEIOEXCEPTION // HERE LOG YOUR ERROR AND GIVE IT TO US >

Check that your «filename» is not a folder. Assess the functionality of your file by recording the outcomes of various assertions.

System.out.println("file exists? " + file.exists()); System.out.println("file is Dir? " + file.isDirectory()); System.out.println("file can be read? " + file.canRead()); 

Insert and Fetch Text from a Text File in Android, Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

Android Save and Write Text File with Intent, getting IOException «No content provider»

Assigning data to a variable called uri is causing confusion, as data is a type of Intent? .

After uri is converted into a Uri? , it can be utilized alongside your null check. Following this, you may use contentResolver.openOutputStream(uri.toString()) to access the OutputStream .

The issue you encountered earlier arose from the fact that you attempted to parse a string representation of Intent as Uri , which is an incompatible operation.

How to create text file and insert data to that file on Android, I try this : File myfile = new File(«genetic_algorithm.txt»); try < String string = "hello world!"; FileOutputStream fos = openFileOutput(myfile

Источник

Читайте также:  Css названия для классов
Оцените статью