Writing numbers to a Java file
I write the array elements to the file
try (FileWriter writer = new FileWriter("C:\\prg1\\Letter.txt", false);) {
for(int i=0;i<mas.length;++i){
writer.write(mas[i]);
writer.write(System.lineSeparator());
}
} catch(IOException ex){
System.out.println(ex.getMessage());
}
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 ?
1
Author: Slava Vedenin, 2016-01-13
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());
}
}
-1
Author: Мстислав Павлов, 2016-01-13 13:55:57
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) {
ArrayList<Integer> list = 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<max){
if(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);
}
}
}
Output:
13
44.END....
-1
Author: Denis Kotlyarov, 2017-04-04 21:53:32