Write number to file java

Java FileWriter

The Java FileWriter class, java.io.FileWriter , makes it possible to write characters to a file. In that respect the Java FileWriter works much like the FileOutputStream except that a FileOutputStream is byte based, whereas a FileWriter is character based. The FileWriter is intended to write text, in other words. One character may correspond to one or more bytes, depending on the character encoding scheme in use. The Java FileWriter class is a subclass of the Java Writer class, by the way.

FileWriter Example

Here is a simple Java FileWriter example:

Writer fileWriter = new FileWriter("data\\filewriter.txt"); fileWriter.write("data 1"); fileWriter.write("data 2"); fileWriter.write("data 3"); fileWriter.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

The FileWriter has other constructors too, letting you specify the file to write to in different ways. Look in the official JavaDoc for more detailed info.

Overwriting vs. Appending the File

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use.

The FileWriter constructor taking just one parameter, the file name, will overwrite any existing file:

Writer fileWriter = new FileWriter("c:\\data\\output.txt");

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file

FileWriter Character Encoding

The FileWriter assumes that you want to encode the bytes to the file using the default character encoding for the computer your application is running on. This may not always be what you want, and you cannot change it!

Читайте также:  Название RSS ленты

If you want to specify a different character encoding scheme, don’t use a FileWriter . Use an OutputStreamWriter on a FileOutputStream instead. The OutputStreamWriter lets you specify the character encoding scheme to use when writing bytes to the underlying file.

write(int)

The Java FileWriter write(int) method writes the lower 16 bit of the int to the destination the FileWriter is connected to, as a single character. Here is an example of writing a single character to a Java FileWriter :

FileWriter fileWriter = new FileWriter("data/output.txt"); fileWriter.write('A');

write(char[])

The Java FileWriter also has a write(char[]) method which can write an array of characters to the destination the FileWriter is connected to. The write(char[]) method returns the number of characters actually written to the FileWriter . Here is an example of writing an array of chars to a Java FileWriter :

FileWriter fileWriter = new FileWriter("data/output.txt"); char[] chars = new char[]; fileWriter.write(chars);

Write Performance

It is faster to write an array of characters to a Java FileWriter than writing one character at a time. The speedup can be quite significant — up to 10 x higher or more. Therefore it is recommended to use the write(char[]) methods whenever possible.

The exact speedup you get depends on the underlying OS and hardware of the computer you run the Java code on. The speedup depends on issues like memory speed, hard disk speed and buffer sizes etc.

Transparent Buffering via BufferedWriter

You can get transparent buffering of bytes written to a Java FileWriter by wrapping it in a Java BufferedWriter . All bytes written to the BufferedWriter will first get buffered inside an internal byte array in the BufferedWriter . When the buffer is full, the buffer is flushed to the underlying FileWriter all at once. Here is an example of wrapping a Java FileWriter in a BufferedWriter :

int bufferSize = 8 * 1024; Writer writer = new BufferedWriter( new FileWriter("c:\\data\\output-file.txt"), bufferSize );

You can read more about the BufferedWriter in my BufferedWriter tutorial.

flush()

The Java FileWriter ‘s flush() method flushes all data written to the FileWriter to the underlying file. The data might be buffered in OS memory somewhere, even if your Java code has written it to the FileWriter . By calling flush() you can assure that any buffered data will be flushed (written) to disk. Here is an example of flushing data written to a Java FileWriter by calling its flush() method:

Closing a FileWriter

When you are finished writing characters to a Java FileWriter you should remember to close it. Closing a FileWriter is done by calling its close() method. Here is how closing a Java FileWriter looks:

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a FileWriter looks with the try-with-resources construct:

try(FileWriter fileWriter = new FileWriter(«data\\filewriter.txt») )

Notice how there is no longer any explicit close() method call to the FileWriter instance. The try-with-resources construct takes care of that.

Источник

Writing numbers to a Java file

The problem is that in the source file » Letter.txt » there are incomprehensible characters instead of numbers. Can you somehow specify the encoding when writing numbers ?

3 answers

The java.io.FileWriter.write method writes to the file not a string representation of a number, but a character with the code contained in that number. Naturally, strange characters appear in the file. To correctly write a string representation of numbers to a file, you must first get this string representation. To do this, you can use the Integer.toString method. The following code illustrates the application of this technique.

import java.io.*; import java.util.Random; class Main < public static void main(String[] args) < int[] array = new int[10]; final Random random = new Random(); for (int i = 0; i < array.length; ++i) array[i] = random.nextInt(); try (final FileWriter writer = new FileWriter("C:/Temp/Letter.txt", false)) < for (int i = 0; i < array.length; ++i) < final String s = Integer.toString(array[i]); writer.write(s); writer.write(System.lineSeparator()); System.out.println(s); >> catch(IOException e) < System.out.println(e.getMessage()); >> > 

This is how it will be correct to write:

public static void main(String[] args) < try < File fileDir = new File("c:\\temp\\test.txt"); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileDir), "UTF8")); out.append("some UTF-8 text").append("\r\n"); out.flush(); out.close(); >catch (UnsupportedEncodingException e) < System.out.println(e.getMessage()); >catch (IOException e) < System.out.println(e.getMessage()); >catch (Exception e) < System.out.println(e.getMessage()); >> 
package javaapplication2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class JavaApplication2 < public static void main(String[] args) < ArrayListlist = new ArrayList<>(); list.add(13); list.add(44); try(FileOutputStream out = new FileOutputStream("file")) < int max = list.size(); if(max >0) < // size >0 out.flush(); //Чистка файла, если надо оставляем int i = 0; int a; while(i 0) < out.write(10); // /n //Выйдет цепочка //13 //44 //ВНИМАНИЕ! В КОНЦЕ ЛИШНЕГО /N НЕТ >a = list.get(i); out.write(Integer.toString(a).getBytes()); i = i + 1; > > > catch (FileNotFoundException ex) < Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex); >catch (IOException ex) < Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex); >//Чтение try(FileInputStream in = new FileInputStream("file")) < //Проще некуда, но на больших файлах это самый плохой вариант byte[] buff = new byte[in.available()]; in.read(buff); System.out.write(buff); System.out.print(".END. "); //В конце закрывающий .END. >catch (FileNotFoundException ex) < Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex); >catch (IOException ex) < Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex); >> > 

Источник

How to write 1 to 1000 numbers into text file using java?

I am fresher candidate. So how to write 1 to 1000 numbers into text file? I tried las below code but it writes as like ASCII values. unable to print as numbers so how to write as numbers?

 import java.io.FileOutputStream; public class FileWriterExample < public static void main(String args[])< try< FileOutputStream fout=new FileOutputStream("D:\\trial.txt"); int i; for(i = 0; i< 1000 ; i++) < fout.write(i); >fout.close(); System.out.println("success. "); >catch(Exception e) > > 

6 Answers 6

You can use PrintWriter and FileWriter to write into the file. You can refer below code for your reference:

public class FileWriterExample < public static void main(String args[]) < try < PrintWriter fileout = new PrintWriter(new FileWriter("C://Users//Desktop//random.txt")); for (int i = 1; i < 1001; i++) < fileout.println(i); >fileout.close(); System.out.println("success. "); > catch (Exception e) < System.out.println(e); >> > 
import java.io.FileOutputStream; class FileWriterExample < public static void main(String args[])< try< FileOutputStream fout=new FileOutputStream("./trial.txt"); int i; for(i = 0; ifout.close(); System.out.println("success. "); >catch(Exception e) > > 

I would like to suggest using a FileWriter (java.io.FileWriter) instead of a FileOutputStream. It assumes that the file being written is a text file.

You might have to explicitly put in the new lines, so your write would look like

And you will still need to declare i to be an integer. Those should be the only change to you code.

this works but only coincidentally because you also convert the integer to a string when appending the newline character

Try this one. I converted the integer value to String and used BufferReader, FileWriter and InpuStreamReader Classes

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class FileWriterExample < public static void main(String[] args) throws IOException < BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new FileWriter("E:\\trial.txt")); try < for(int i = 0; i< 1000 ; i++) < // in here value will be written as String format out.write(String.valueOf(i)); // goes to new line if want out.newLine(); >System.out.print("Write Successful"); > catch(IOException e1) < System.out.println("Error during reading/writing"); >finally < out.close(); in.close(); >> > 

With PrintStream or PrintWriter you can print all basic types directly without needing to convert to String beforehand:

 public static void main(String args[]) < try< FileOutputStream fout = new FileOutputStream("D:\\trial.txt"); PrintStream pout = new PrintStream(fout); int i; for(i = 0; i< 1000 ; i++) < pout.println(i); >pout.close(); System.out.println("success. "); > catch(Exception e) < System.out.println(e); >> 

You can use the following two functions to do the job. Both will write the numbers separated by spaces.

The first function will always append the numbers to the file. The second function will write the numbers discarding the previous content of the file. You can use them according to your requirement.

public static void writeNums(int[] arr, File file) throws Exception < FileWriter fw = new FileWriter(file, true); for(int x:arr)< fw.write(Integer.toString(x)); fw.write(" "); >fw.close(); > public static void writeNums(int[] arr, File file) throws Exception < PrintWriter pw = new PrintWriter(file); for(int x:arr)< pw.format("%d ", x); >pw.close(); > 

Источник

Writing a long (primitive type) to a file in Java

Hi all, I have an array of long that I would like to write into a .txt file that I can later open in gedit (one number per line). I get those values by using a subtraction of two instances of System.currentTimeMillis(). I use the following code:

BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt")); for (int i = 0; i < USER_LIMIT; ++i) < out.write(latency[i] + "\n"); >out.close(); 

I believe the string concatenation converted the long into an integer. If I use the DataOutputStream, then I cannot read it back with gedit or any notepad/text editor, it just looks like garbage (I believe it’s writing bytes). Would anyone please let me know how I can fix my problem please? Thank you very much!

I actually did not check the value of latency[i], and I should have (my bad). I will look at it right now. I assumed because the system returns milliseconds that 1 was way to small. Let me double check the values.

4 Answers 4

There is nothing wrong with your code. What you think is in latency . isn’t.

public static void main(String[] args) throws IOException < long[] latency = < 123456789000L, 234567890000L, 345678901000L >; BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt")); for (int i = 0; i < 3; ++i) < out.write(latency[i] + "\n"); >out.close(); > 
$ more latency.txt 123456789000 234567890000 345678901000 

When you’re having a problem with code like this, it’s often beneficial to write a small test case to narrow down the problem.

Cast to a Long and use toString:

out.write(((Long)latency[i]).toString() + "\n"); 

Or just use the static toString:

out.write(Long.toString(latency[i]) + "\n"); 

When you use DataOutputStream to write a long it is using a different encoding of your data than gedit understands.

One of the most common encodings used for text files is ASCII. With this each byte represents a character in a table. This table has 128 characters. When you write a string to a file using Java the way you’re doing it this is what is happening and gedit understands that encoding. If you convert a long to a string the maximum size a long can be would look like: 9223372036854775807. That would take up 19 bytes.

A long in Java is 64 bits or 8 bytes. When you use DataOutputStream a long gets written to the file as 8 bytes. A text editor like gedit does not understand this encoding.

What further complicates things is encodings such as UTF-8.

Источник

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