Store data to file java

Как записать данные в файл

В этой статье мы рассмотрим различные способы записи текстовой и бинарной информации в файл, используя стандартные API Java.

Запись текста в файл (Java 7 и выше)

Первый способ годится, если вы используете Java 7 и выше. Здесь используется класс Paths, который был добавлен в Java 7. Данный код перезапишет информацию в файле, если тот уже существует.

// запись в файл текстовой информации (файл перезаписывается) List lines = Arrays.asList("Привет", "Мир"); Path file = Paths.get("output.txt"); Files.write(file, lines, StandardCharsets.UTF_8);

Если же вам нужно добавить текст в конец файла, укажите дополнительную опцию StandardOpenOption.APPEND:

// запись в файл текстовой информации (информация добавляется в конец файла) List lines2 = Arrays.asList("Привет", "Мир"); Path file2 = Paths.get("output.txt"); Files.write(file2, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Запись бинарной информации в файл

Если вам требуется записать не текстовые данные, а бинарные данные, используйте следующий пример. В качестве бинарных данных может выступать любой массив байтов (например, байтовое представление картинки или любого другого файла).

// запись в файл бинарной информации (файл перезаписывается) byte[] data = "Бинарные данные".getBytes(); Path fileB = Paths.get("output.bin"); Files.write(fileB, data);

Для того, чтобы добавить информацию в конец файла, не перезаписывая его полностью, ипользуйте этот код:

// запись в файл бинарной информации (информация добавляется в конец файла) byte[] data2 = "Бинарные данные".getBytes(); Path fileB2 = Paths.get("output.bin"); Files.write(fileB2, data, StandardOpenOption.APPEND);

Если же вы используете Java 6 ниже, воспользуйтесь следующими примерами.

Читайте также:  javaScript Digital Clock with date

Запись текста в файл (Java 6)

Этот код запишет данные в файл (причём если файл существует, данные в нём будут перезаписаны).

// если файл существует, он перезатрётся PrintWriter writer = new PrintWriter("output.txt", "UTF-8"); writer.println("Первая строка"); writer.println("Вторая строка"); writer.close();

Если вам нужно дописать текст в конец файла, используйте следующий код:

// здесь мы допишем информацию в конец файла, если он уже существует PrintWriter writer2 = new PrintWriter((new FileWriter("output.txt", true))); writer2.println("Третья строка"); writer2.close();

Для записи бинарных данных в файл в Java 6 используйте следующий код (информация в файле перезапишется):

// запись в файл бинарной информации (файл перезаписывается) OutputStream os = new FileOutputStream("output.bin"); byte[] data = "какие-то бинарные данные".getBytes(); os.write(data); os.close();

Для добавления бинарных в конец файла в Java используйте следующий код:

// запись в файл бинарной информации (информация добавляется в конец файла) OutputStream osB = new FileOutputStream("output.bin", true); byte[] dataB = "какие-то бинарные данные".getBytes(); osB.write(dataB); osB.close();

Резюме

В этой статье мы рассмотрели различные способы записи в файл текстовой и бинарной информации. Данные примеры используют стандартные возможности Java и не требуют подключения дополнительных библиотек.

Источник

Java Write to File — 4 Ways to Write File in Java

Java Write to File - 4 Ways to Write File in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.

Java Write to File

java write to file, write file in java

Let’s have a brief look at four options we have for java write to file operation.

  1. FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
  2. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
  3. FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
  4. Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.

Java Write to File Example

Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java

package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFile < /** * This class shows how to write file in java * @param args * @throws IOException */ public static void main(String[] args) < String data = "I will write this String to File in Java"; int noOfLines = 10000; writeUsingFileWriter(data); writeUsingBufferedWriter(data, noOfLines); writeUsingFiles(data); writeUsingOutputStream(data); System.out.println("DONE"); >/** * Use Streams when you are dealing with raw data * @param data */ private static void writeUsingOutputStream(String data) < OutputStream os = null; try < os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); >catch (IOException e) < e.printStackTrace(); >finally < try < os.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use Files class from Java 1.7 to write files, internally uses OutputStream * @param data */ private static void writeUsingFiles(String data) < try < Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes()); >catch (IOException e) < e.printStackTrace(); >> /** * Use BufferedWriter when number of write operations are more * It uses internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines */ private static void writeUsingBufferedWriter(String data, int noOfLines) < File file = new File("/Users/pankaj/BufferedWriter.txt"); FileWriter fr = null; BufferedWriter br = null; String dataWithNewLine=data+System.getProperty("line.separator"); try< fr = new FileWriter(file); br = new BufferedWriter(fr); for(int i = noOfLines; i>0; i--) < br.write(dataWithNewLine); >> catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); fr.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use FileWriter when number of write operations are less * @param data */ private static void writeUsingFileWriter(String data) < File file = new File("/Users/pankaj/FileWriter.txt"); FileWriter fr = null; try < fr = new FileWriter(file); fr.write(data); >catch (IOException e) < e.printStackTrace(); >finally < //close resources try < fr.close(); >catch (IOException e) < e.printStackTrace(); >> > > 

These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.

You can checkout more Java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Store data in text file java code example

Because this lib has a StringUtils class which has a large method base for checking the content of string IOUtils class for reading files easily Additionally I would use simple regular expression groups to identify your text parts. Solution 2: «[S]tore data in text file» sounds like you want a readable format.

Storing data in text file

You may want to read the answer on creating and writing to a file in java.

// One creates the PrintWriter to print to a place. PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); // Then one prints each line. If you have an array of lines, you can print by iterating through that array. writer.println("The first line"); writer.println("The second line"); // Remember to close the writer. Though, if you use `try-with-resources`, that is no longer a problem. writer.close(); 

If you know what information you have and what format you want it saved into, simply write it out to disc. Your code in the try loop is unrevealing about what kind of information you want to write, so I can’t say more than this.

Java Create and Write To Files, Dark code. ×. Tutorials. HTML and CSS Java Data Types. In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

How to store data in text file in java

It sounds like the Java class that will suit you best is a FileWriter. However, if you are writing a file with Key=Value lines, then the Properties class might end up being the better choice.

«[S]tore data in text file» sounds like you want a readable format. You can use comma-separated value (CSV) files.

You can write your own CSV serializer (search on SO for «how to write csv java») or use a solution like the Java CSV library.

Use DataOutputStream and DataInputStream. Using this class make it easier to read integer, float, double data and others without needing to interpret if the read data should be an integer or a float data.

DataOutputStream dos = new DataOutputStream(fos);

 // // Below we write some data to the cities.dat. // DataOutputStream class have various method that allow // us to write primitive type data and string. There are // method called writeInt(), writeFloat(), writeUTF(), // etc. // dos.writeInt(cityIdA); dos.writeUTF(cityNameA); dos.writeInt(cityPopulationA); dos.writeFloat(cityTempA); dos.writeInt(cityIdB); dos.writeUTF(cityNameB); dos.writeInt(cityPopulationB); dos.writeFloat(cityTempB); dos.flush(); dos.close(); 

Reading from a text file and storing in a String, How can we read data from a text file and store in a String Variable? Err, read data from the file and store it in a String variable. It’s just code. Not a real question so far. Is it possible to pass the filename in a method and it would return the String which is the text from the file. Yes it’s possible. It’s also a very bad idea.

Read from text file and store to collection

You should start with creating a book class:

You have a class for your books now which you can store in an array list of books. In your readBooks method you should create this array list:

ArrayList bookList = new ArrayList<>(); 

Now you use this list inside your processBook method. You create your Book object with the constructor I defined erlier:

Book book = new Book(title, author, bookISBN, callNumber, type, noOfCopy); 

You can add this Book to your arrayList now:

This will store your books in a collection.

I would create a class. For example:

and add a new Bookinstance to an Arraylist.

List books= new ArrayList(); books.add(new Book(id, parts[0], parts[1], parts[2], parts[3], parts[4], parts[5])) 

I think the best approach will be to create a Book class, like the following:

public class Book < private String title; private String author; private String bookISBN; private String callNumber; private String type; private long noOfCopy; public String getTitle() < return title; >public void setTitle(String title) < this.title = title; >public String getAuthor() < return author; >public void setAuthor(String author) < this.author = author; >public String getBookISBN() < return bookISBN; >public void setBookISBN(String bookISBN) < this.bookISBN = bookISBN; >public String getCallNumber() < return callNumber; >public void setCallNumber(String callNumber) < this.callNumber = callNumber; >public String getType() < return type; >public void setType(String type) < this.type = type; >public long getNoOfCopy() < return noOfCopy; >public void setNoOfCopy(long noOfCopy) < this.noOfCopy = noOfCopy; >> 

Then just create new objects at the processBook :

Book tempBook = new Book(); tempBook.setTitle(title); . 

And add them to the List , for example:

List myList = new ArrayList<>(); . myList.add(tempBook); 

Java — How to write code data into a text file, here’s a tutorial on how to do it, its really simple. When you serialize an object you can write it onto a file and then load it as it is from there . EDIT : example on how you could use this here , i guess the ObjectClass is the thing u want to save so : class ObjectClass implements Serializable < String name; String number; …

Storing data from text into variables

I would recommend the Apache Commons Lib here very much. Because this lib has a

  • StringUtils class which has a large method base for checking the content of string
  • IOUtils class for reading files easily

Additionally I would use simple regular expression groups to identify your text parts.

See Pattern and Matcher class for details. (Regex for Words: «\w» Digits «\d»)

If you really don’t know what each type might be, you have to store every field as String as a number like 1000 could be a short, int, long, float, double or String. Is 1 a number , String or the character ‘1’? Without context you cannot know what each type is. a , b and c could be a numbers in hexidecimal. 😉

It would take me longer to say what I would do differently, than it would to re-write the code. 😉

public class CopyToString < static class Line < String word; int num1, num2; Line(String word, int num1, int num2) < this.word = word; this.num1 = num1; this.num2 = num2; >@Override public String toString() < return "Line'; > > public static void main(String. args) throws IOException < String fileSpecified = args[0] + ".txt"; System.out.println("file Specified = " + fileSpecified); BufferedReader br = new BufferedReader(new FileReader(fileSpecified)); Listlines = new ArrayList(); for (String line; (line = br.readLine()) != null;) < Scanner scanner = new Scanner(line); lines.add(new Line(scanner.next(), scanner.nextInt(), scanner.nextInt())); >br.close(); for (Line l : lines) System.out.println(l); > > 
file Specified = text.txt Line Line Line

Java program to store a Student Information in a File, First, we need to create a frame using JFrame. Next create JLabels, JTextFields, JComboBoxes, JButtons and set their bounds respectively. Name these components accordingly and set their bounds. Now, in order to save the data into the text file on button click, we need to add Event Handlers. In this case, we …

Источник

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