I'm trying to write a series of 10000 random integers to a text file using a byte stream, however once I open the text file up it has a collection of random characters which seemingly have little to do with the integer values I want to be shown. I'm new to this form of stream, I'm guessing that the integer values are being taken as byte values, but I can't think of a way to get round this.
My current attempt...
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class Question1ByteStream {
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("ByteStream.txt");
try {
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
int by = randomNumber.byteValue();
out.write(by);
}
}finally{
if (out != null) {
out.close();
}
}
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Apologies if this lacks clarity.
It's because the numbers that you write are not written as strings into the txt but as raw byte value.
Try the following code:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write(yourRandomNumberOfTypeInteger.toString());
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Or, if referring to your original code, write the Integer directly:
try {
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
out.write(randomNumber.toString());
}
}finally{
if (out != null) {
out.close();
}
}
dont do like below(writing in the form of byte characters)
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
int by = randomNumber.byteValue();
out.write(by);
}
write it in the form of string as it is a text file
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
out.write(randomNumber);
}
automatically toString() method will be called for Integer Object randomNumber
and it will be written to file.
Related
I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}
In this programmer i found Prime numbers in first 100.Numbers are in INT format and totally number of them is in DOUBLE format.I want to read that file and i did it for only INT numbers but i dont know hot to do it for DOUBLE number.
Here is the code:
package int1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;
public class int_upis {
public static void main(String[] args) {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(a);
} catch (Exception e) {
}
FileChannel ch = fos.getChannel();
ByteBuffer bff = ByteBuffer.allocate(100);
IntBuffer ibf = bff.asIntBuffer(); // Int type
DoubleBuffer db = bff.asDoubleBuffer(); // Double type
double p = 0;
for (int i = 1; i <= 100; i++) {
int t = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
t = t + 1;
}
}
if (t < 3) {
p = p + 1; // number of Prime numbers
System.out.println(i);
ibf.put(i);
bff.position(4 * ibf.position());
bff.flip();
try {
ch.write(bff);
bff.clear();
ibf.clear();
} catch (IOException e) {
}
}
}
try {
db.put(p); //At the end of the txt-file i put double format of number (Number of Prime numbers)
bff.position(8*db.position());
bff.flip();
ch.write(bff);
System.out.println("File is writen with: " + ch.size());
ch.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now I tried to read this file:
public class int_ispis {
public static void main(String[] args) throws IOException {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(a);
} catch (Exception e) {
}
FileChannel ch = fis.getChannel();
ByteBuffer bff = ByteBuffer.allocate(6 * 4);
This is one line of Prime Number put in a 6-row array (this line below):
int[] niz = new int[6];
System.out.println("Pre flipa: " + bff.position() + " " + bff.limit());
System.out.println("++++++++++++++++++++++++++++++++++++");
while (ch.read(bff) != -1) {
bff.flip();
System.out.println();
System.out.println("Posle flipa: " + bff.position() + " " + bff.limit());
IntBuffer ib = bff.asIntBuffer();
System.out.println("IB: " + ib.position() + " " + ib.limit());
int read = ib.remaining();
System.out.println(read);
When it come to the end of file it puts Double Number as Integer and writes wrong number(How to separate Integer form Double number?)
ib.get(niz, 0, ib.remaining());
for (int i = 0; i < read; i++) {
System.out.print(niz[i] + " ");
}
System.out.println();
System.out.println("=================================");
ib.clear();
bff.clear();
}
}
}
A binary file does not have any "separators".
You need to know the structure of the file content and use this knowledge.
In this programmer i found Prime numbers in first 100.Numbers are in INT format and totally number of them is in DOUBLE format.
This means that there is only one long value in the file and this is in the last 8 bytes. So you simply have to check if the current position is fileLenght - 8 and then read these last 8 bytes as a long value.
I have a text file of data like this
username=Ayyappa,password=123
username=venkata,password=456
username=Bhargav,password=789
username=Rama,password=158
username=Pusarla,password=968
i want to print the data at row number 2
(My expected output is username=venkata,password=456)
Funtion written:
public class TestDataReader {
public static String getrowvalue(String FileName, int rownum) throws IOException{
FileReader fr = new FileReader(FileName);
BufferedReader br = new BufferedReader(fr);
String lineString = null;
while((lineString = br.readLine())!= null){
int counter = 1;
if(counter == rownum){
System.out.println(lineString);
counter ++;
}
}
return lineString;
}
}
i called this function in another class
TestDataReader.getrowvalue("F:\WS_Finsys_Ayyappa\Ejagruti\TestData\login.txt", 2);
but when i am calling this function it is printing all the row data but not with row data i passed in this case i passed rownum 2 to get the row data
Your mistake is here: you simply flush counter value each time in loop:
int counter = 1;
So change it to:
int counter = 1;
while((lineString = br.readLine())!= null){
if(counter == rownum){
System.out.println(lineString);
}
counter++;
}
UPD: Also, as #Lemm Ras mentioned, you have to move counter incrementation outside if statement.
Java 8 solution:
For small files:
String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
For large files:
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line32 = lines.skip(31).findFirst().get();
}
A simple one ,Java <8 solution:
public String readLine(int line){
FileReader tempFileReader = null;
BufferedReader tempBufferedReader = null;
try { tempFileReader = new FileReader(textFile);
tempBufferedReader = new BufferedReader(tempFileReader);
} catch (Exception e) { }
String returnStr = "ERROR";
for(int i = 0; i < line - 1; i++){
try { tempBufferedReader.readLine(); } catch (Exception e) { }
}
try { returnStr = tempBufferedReader.readLine(); } catch (Exception e) { }
return returnStr;
}
i am trying to find standard deviation(σ = √[(Σ(x - MEAN))2 ÷ n]) of single extracted column of csv file.csv file contain around 45000 instance and 17 attribute saperated with ';'.
for finding standard deviation it need MEAN value in every iteration of while loop for substact with Xi. so i think MEAN need before while loop iteration for find standard deviation.but i dont know how to do this or is there any way to do this. am getting stuck here. then i had puted code for replace old Xi with new Xi. and then write(generate) new csv file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import java.io.*;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) throws IOException {
String filename = "ly.csv";
File file = new File(filename);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("bank-full_updated.csv"));
}
catch (IOException e) {
}
try {
double Tuple,avg;
double temp;
Tuple = 0;
double stddev=0;
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data1 = inputStream.next();
String[] values = data1.split(";");
double Xi = Double.parseDouble(values[1]);
//now finding standard deviation
temp1 += (Xi-MEAN);
// temp2=(temp1*temp1);
// temp3=(temp2/count);
// standard deviation=Math.sqrt(temp3);
Xi=standard deviation * Xi
//now replace new Xi to original values1
values[1] = String.valueOf(Xi);
// iterate through the values and build a string out of them for write a new file
StringBuilder sb = new StringBuilder();
String newData = sb.toString();
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < values.length - 1) {
sb.append(";");
}
}
// get the new string
System.out.println(sb.toString());
writer.write(sb.toString()+"\n");
}
writer.close();
inputStream.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
It is possible to calculate the standard deviation in a single pass. Professor Donald Knuth has an algorithm that does it using the Kahan summation. Here is the paper: http://researcher.ibm.com/files/us-ytian/stability.pdf
Here is another way but it suffers from rounding errors:
double std_dev2(double a[], int n) {
if(n == 0)
return 0.0;
double sum = 0;
double sq_sum = 0;
for(int i = 0; i < n; ++i) {
sum += a[i];
sq_sum += a[i] * a[i];
}
double mean = sum / n;
double variance = sq_sum / n - mean * mean;
return sqrt(variance);
}
I am writing code for a game in Java. Specificly I'm working on the level creation using a character array filled by characters from a .txt file. My problem is that the array is not filled as it should be and the final line remains empty. I can't work this out so any kind of help will be gladly accepted, here's the problematic block of code :
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<19;j++){
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}
Also the code as a whole can be found in the following link: http://pastebin.com/HtwMpsjm
Here's the .txt file too!
You accidentally one of your conditions, i've commented on the changed line.
As someone has mentioned in the comments, you might find it beneficial to treat your loops conditions as for(int i=0;i<20;i++) rather than for(int i=0i<=19;i++) it makes the code a little more readable.
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<=19;j++){//<<THIS LINE WAS CHANGED
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}
Why do we need multiple for loops here. If you want to read characters from a file you could use buffered reader and the this matrix could be created in one line of code like while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ }. Also you are using a while loop to read one char and then an unconditional break statment inside is not a good practice (in my opinion). Try
public static void main(String[] args) throws IOException {
char background[][] = new char[14][20];
try {
FileReader fileReader = new FileReader("background.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i=0;
while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ } // This like created your 2D array
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i <= 13; i++) {
for (int j = 0; j <= 19; j++) {
System.out.print(background[i][j]);
}
}
}