Answer the question
In order to leave comments, you need to log in
Why does the program write hieroglyphs to a file instead of numbers?
Having nothing to do, I decided to make a program that takes numbers from a file and rounds them to integers. For example 3.151361 = 3, 13.836724 = 14 etc. But instead of integers, he writes hieroglyphs, like this:
What's the problem? First time I'm facing this.
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
public class Main {
BufferedReader reader = null;
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
ArrayList<Double> doubleNumbers = new ArrayList<Double>();
ArrayList<BigInteger> intNumbers = new ArrayList<BigInteger>();
int count = 0;
public static void main(String[] args) throws IOException {
Main main = new Main();
main.start();
}
public void start() throws IOException {
readFile();
okryglenieChisel();
writeFile();
}
public String readFilesName() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Введите название файла " + ++count);
String fileName = reader.readLine();
return fileName;
}
public void readFile() throws IOException {
inputStream = new FileInputStream(readFilesName());
String s = "";
while (inputStream.available() > 0) {
char d = (char) inputStream.read();
if (d != ' ') { //Да, да, это не лучший метод, лучше разбить их методом split, это сделаю позже
s += d;
} else {
doubleNumbers.add(Double.parseDouble(s));
s = "";
}
}
}
public void writeFile() throws IOException{
outputStream = new FileOutputStream(readFilesName());
for (BigInteger i : intNumbers) {
Integer integ = new Integer(i.intValue());
outputStream.write(integ);
}
}
public void okryglenieChisel() {
for (Double x : doubleNumbers) {
BigDecimal dec = new BigDecimal(x);
intNumbers.add(dec.toBigInteger());
}
}
}
Answer the question
In order to leave comments, you need to log in
The FileOutputStream class writes "bare bytes" to the file. Moreover, your ints are truncated to a byte.
@Override
public void write(int oneByte) throws IOException {
write(new byte[] { (byte) oneByte }, 0, 1);
}
public synchronized void print(String str) {
if (out == null) {
setError();
return;
}
if (str == null) {
print("null");
return;
}
try {
if (encoding == null) {
write(str.getBytes());
} else {
write(str.getBytes(encoding));
}
} catch (IOException e) {
setError();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question