Save program in java

Java “file write” (or “file save”) methods

Java write/save FAQ: Can you share an example of how to write to a file in Java?

Sure. Here are two «Java file save» or «Java file write» examples, taken from my Java file utilities article (Java file utilities to write, save, open, read, and copy files). I’m not going to explain these too much, but if you need a simple method to write to a file in your Java programs, I hope these methods will help you.

1) A Java «save file as text» example

This first Java method lets you write plain text (a String) to a file:

/** * Save the given text to the given filename. * @param canonicalFilename Like /Users/al/foo/bar.txt * @param text All the text you want to save to the file as one String. * @throws IOException */ public static void writeFile(String canonicalFilename, String text) throws IOException

Читайте также:  Парк высоких технологий html

2) A Java save/write binary data to file example

This second Java file-writing method lets you write an array of bytes to a file in Java (binary data), using the FileOutputStream and BufferedOutputStream classes:

/** * Write an array of bytes to a file. Presumably this is binary data; for plain text * use the writeFile method. */ public static void writeFileAsBytes(String fullPath, byte[] bytes) throws IOException < OutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fullPath)); InputStream inputStream = new ByteArrayInputStream(bytes); int token = -1; while((token = inputStream.read()) != -1) < bufferedOutputStream.write(token); >bufferedOutputStream.flush(); bufferedOutputStream.close(); inputStream.close(); >

That method can be good if you want to write binary data to a file using Java.

I hope these «Java file write» example methods will help in your own Java file programming needs.

Источник

How to redirect Output of a Program to a Text file in Java

In this tutorial, we will learn how to redirect or save the output of a Program to a Text file in Java. There are many ways of doing this. One method I find simple is by the use of PrintWriter class.

Explanation

  1. FileOutputStream is an output stream, we can use to write data to a file.
  2. We can use PrintWriter to write formatted text to a file.
  3. Then we write the code and parse the output to a string.
  4. When the code is executed, a new file is created and the program output is written to the file by the use of PrintWriter write method.
  5. If the operation is successful we display the success message.
  6. Else if we encounter an IO Exception we print the error message on the console.

Code to Save Output of a Program to a Text file in Java

import java.util.*; import java.io.*; class Output < public static void main(String args[]) < try < File f = new File("Output.txt"); FileOutputStream fos = new FileOutputStream(f); PrintWriter pw = new PrintWriter(fos); int[]arr = ; Arrays.sort(arr); String s = ""; for(int i = 0; i < arr.length; i++) < s = s + arr[i] + ","; >pw.write(s); pw.flush(); fos.close(); pw.close(); System.out.println("Output Written to file"); > catch(IOException ex) < ex.printStackTrace(); >> >

Output:

Save Output of a Program to a Text file in Java

An output.txt file is created when the program is executed:

When we open the output.txt file, we can find the output of the program, we just executed.

output.txt

Hope you understood the code 🙂
Any questions please feel free to drop in your comments.

Источник

How to save data in a Java program

PrintWriter class is used to write the string data on file using the write() method. Files class is having a predefined write() method which is used to write a specified text to the file.

How to save data in a Java program

Is there a way to make a collection of class files/objects and then have them used in an interactive main file? So let’s say I want to make a program to store information interactively where different classes are designed to hold different information. Then I would have an interactive main file where I made instances of these classes which would collectively hold the information I want stored. And then any changes or anything I do in this interactive main file is then saved.

I understand that this might be a very odd inquiry and maybe some other program might be useful for this. If so, feel free to point me in the right direction.

Here are two solutions that are good for the purpose you mentioned in your comment.

The first one is called Serialization. This let’s you save your java object to your hard drive, and retrieve it later.

The second, (and in this case, more preferable option in my opinion), is using a Database.

A database is a compliment to your program, that stores data. You can then use «Queries» to access this data, and update it. Almost every database software is compatible with java.

The reason I think a database would be better for your purpose is that they are already highly optimized, and are designed to have multiple people accessing and writing to them at once. If you wanted just want one person to use this program at a time however, serialization might be easier to implement.

Absolutely! Your main class would use the standard input (perhaps Scanner input = new Scanner(System.in); ) and output ( System.out.println() ). To interact with your other classes, most simply, just put them in the same folder (if you are interested take a look at Java packages ). If you have a Dog class in the same folder as your main class, you can freely create Dog objects in your main class. I hope this helps!

As a side note, because you mentioned storing information with different classes, you might be interested in the Java Collections Framework.

Using Java to save to and read from a file, Reading and writing text files in Java. Using the hasNextLine method to control the loop. Using Duration: 24:02

How to Save/Load Data with Text File (1/2)

Previous: https://youtu.be/-BBC_tJkD_ENext: https://youtu.be/6y6aWvi-OvMOn this video, I’ll
Duration: 17:57

How to Save/Load Data with DAT file

In this video I will explain how to save/load your game data to/from dat file.1I kind of messed up Duration: 13:53

Using Java to save to and read from a file

Reading and writing text files in Java. Using the hasNextLine method to control the loop. Using Duration: 24:02

Save data permanently in Java (and load it automatically)? [duplicate]

I’d like to save data (just String that could be stored in a small text file) and load it automatically to the app when it is started. I imagine a text file in the program installed directory but I dont know if it is possible. How could the program know the path of the directory where it is installed? Or should I just ask for the first time the user to tell the program the location and somehow the program save this location info?

And it should be work on Windows, Mac and Linux.

I generally use System.getProperty(«user.home») to get the default home directory on different platforms. One easy and reliable way would be to use something like:

String fileLocation = new StringBuilder(System.getProperty("user.home")) .append(File.separator) .append("myApplicationDir") .append(File.separator) .append("fileName.txt") .toString(); 

. and load it automatically to the app when it is started

I would suggest suggest to store a file with meta data stored relative to the JAR . Or you can just keep a utility class with static constant stored in order to find out what the application stored directory is and then use it to retrieve it when the constructor of any object is invoked or on any callback.

Cant save data into Firestore, The Firebase authentication operation is asynchronous. This means that you can be sure that authentication succeeded only when the

Java Program to Save a String to a File

A demo file on the desktop named ‘gfg.txt’ is used for reference as a local directory on the machine. Creating an empty file before writing a program and give that specific path of that file to the program.

  1. Using writeString() method of Files class
  2. Using write() method of Files class
  3. Using writer() method of Filewriter class
  4. Using write() method of Bufferedwriter class
  5. Using write() method of printwriter class

Let us discuss every method individually by implementing the same via clean java programs to get a fair idea of working on them.

Method 1: Using writeString() method of Files class

The writeString() method of File Class in Java is used to write contents to the specified file. ‘ java.nio.file.Files’ class is having a predefined writeString() method which is used to write all content to a file, using the UTF-8 charset.

Files.writeString(path, string, options)
  • Path: File path with data type as Path
  • String: A specified string that will enter in the file with a return type string.
  • Options: Different options to enter the String in the File. Like append the string to the file, overwrite everything in the file with the current string, etc

Return Value: This method does not return any value.

  • Create an instance of the file.
  • Call the Files.writeString() method with an instance, string and characters set.

Источник

In Java How to Save and Load Data from a File – Simple Production Ready Utility for File I/O Read-Write Operation

In Java How to Save and Load Data from a File - Simple Production Ready Utility for File I:O Read-Write Operation

Java is pretty amazing with lots of API and with Java 8 we are fully enabled with lots more APIs like Lambda, Method reference, Default methods, Better type interface, Repeating annotations, Method parameter reflections and lot more.

Sometime back I’ve written an article on How to Read JSON Object From File in Java. It was simple java read operation. But in this tutorial we are going to save and load data from file with simple Production Ready Java Utility.

Simple Production Ready utility for File Read:Write Operation

We are not only saving simple object but we will create simple Java POJO of type CrunchifyCompany and going to save and retrieve object using GSON . You need below dependency in order for below program to run.

Put below dependency to your maven project. If you have Dynamic Web Project and want to convert it into Maven project then follow these steps.

 com.google.code.gson gson 2.3  

Here is a flow:

  • Create class CrunchifyReadWriteUtilityForFile.java
  • Create private inner class CrunchifyCompany with two fields
    • private int employees ;
    • private String companyName ;

    Here is a complete example:

    package crunchify.com.tutorial; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Crunchify.com * Best and simple Production ready utility to save/load * (read/write) data from/to file */ public class CrunchifyReadWriteUtilityForFile < private static final String crunchifyFileLocation = "/Users/appshah/Documents/crunchify.txt"; private static final Gson gson = new Gson(); // CrunchifyComapny Class with two fields // - Employees // - CompanyName private static class CrunchifyCompany < private int employees; private String companyName; public int getEmployees() < return employees; >public void setEmployees(int employees) < this.employees = employees; >public String getCompanyName() < return companyName; >public void setCompanyName(String companyName) < this.companyName = companyName; >> // Main Method public static void main(String[] args) < CrunchifyCompany crunchify = new CrunchifyCompany(); crunchify.setCompanyName("Crunchify.com"); crunchify.setEmployees(4); // Save data to file crunchifyWriteToFile(gson.toJson(crunchify)); // Retrieve data from file crunchifyReadFromFile(); >// Save to file Utility private static void crunchifyWriteToFile(String myData) < File crunchifyFile = new File(crunchifyFileLocation); // exists(): Tests whether the file or directory denoted by this abstract pathname exists. if (!crunchifyFile.exists()) < try < File directory = new File(crunchifyFile.getParent()); if (!directory.exists()) < // mkdirs(): Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. // Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. directory.mkdirs(); >// createNewFile(): Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. // The check for the existence of the file and the creation of the file if it does not exist are a single operation // that is atomic with respect to all other filesystem activities that might affect the file. crunchifyFile.createNewFile(); > catch (IOException e) < crunchifyLog("Exception Occurred: " + e.toString()); >> try < // Convenience class for writing character files FileWriter crunchifyWriter; crunchifyWriter = new FileWriter(crunchifyFile.getAbsoluteFile(), true); // Writes text to a character-output stream BufferedWriter bufferWriter = new BufferedWriter(crunchifyWriter); bufferWriter.write(myData.toString()); bufferWriter.close(); crunchifyLog("Company data saved at file location: " + crunchifyFileLocation + " Data: " + myData + "\n"); >catch (IOException e) < crunchifyLog("Hmm.. Got an error while saving Company data to file " + e.toString()); >> // Read From File Utility public static void crunchifyReadFromFile() < // File: An abstract representation of file and directory pathnames. // User interfaces and operating systems use system-dependent pathname strings to name files and directories. File crunchifyFile = new File(crunchifyFileLocation); if (!crunchifyFile.exists()) crunchifyLog("File doesn't exist"); InputStreamReader isReader; try < isReader = new InputStreamReader(new FileInputStream(crunchifyFile), StandardCharsets.UTF_8); JsonReader myReader = new JsonReader(isReader); CrunchifyCompany company = gson.fromJson(myReader, CrunchifyCompany.class); crunchifyLog("Company Name: " + company.getCompanyName()); int employee = company.getEmployees(); crunchifyLog("# of Employees: " + Integer.toString(employee)); >catch (Exception e) < crunchifyLog("error load cache from file " + e.toString()); >crunchifyLog("\nCompany Data loaded successfully from file " + crunchifyFileLocation); > private static void crunchifyLog(String string) < System.out.println(string); >>

    Eclipse Console Output:

    Company data saved at file location: /Users/appshah/Documents/crunchify.txt Data: Company Name: Crunchify.com # of Employees: 4 Company Data loaded successfully from file /Users/appshah/Documents/crunchify.txt

    Here is a crunchify.txt file content.

    As I ran program two times you see here JSONObject two times as we are appending value to crunchify.txt file.

    How to Save Object to File in Java - Crunchify

    If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

    Suggested Articles.

    Источник

Оцените статью