I have written this program to write marks into the file called marks.txt, but why is the dos.writeInt() writing Ascii values into the file?
class Q5marks
{
public static void main(String a[])throws IOException`
{
int marks[]=new int[6]
File file = new File("marks.txt");
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
Scanner sc = new Scanner(System.in);
for(int i = 0;i<6;i++)
{
marks[i]=sc.nextInt();
System.out.println("marks "+(i+1)+" =>" +marks[i]);
dos.writeInt(marks[i]);
}
}
}
Replace your code with : dos.writeBytes(marks[i]+""); . It should work as desired by you .
i want to insert 65 65 65 65 65 65 but it writes A A A A A A into the file
Then you should be using PrintStream and not DataOutputStream.
It will write numerical values to the file because you've specified writeInt.
You may be looking to use:
doc.writeChar(marks[i]);
But I can't be too sure. Your question isn't quite clear enough.
Instead, use as PrintStream.
When you call dos.writeInt(marks[i]); don't think that it will write the int in human readable format( as normal text editor consider all as char so your 65 become A). It will write the byte value of int. You can read the file again using the readInt() method.
EDIT:
If you want it should write the int show that you can read it with normal text editor then
use the flowing code that use a FileWriter instead of DataOutputStream. And don't forget to close the writer.
class Q5marks
{
public static void main(String a[])throws IOException
{
int marks[]=new int[6];
File file = new File("marks.txt");
FileOutputStream fos = new FileOutputStream(file);
FileWriter writer=new FileWriter(file);
Scanner sc = new Scanner(System.in);
for(int i = 0;i<6;i++)
{
marks[i]=sc.nextInt();
System.out.println("marks "+(i+1)+" =>" +marks[i]);
writer.write(String.valueOf(marks[i])+" ");//a space is added to increase the readability
}
writer.close();
}
}
Related
Evening, I have this need:
Every output of the console should be printed into a file but also still in the console. and the /n should be changed with lineSeparator().
How can I achieve that?
You can assign a PrintStream to System.out with System.setOut().
Thus you have to implement a PrintStream that outputs its input to the old System.out and a file simultaneously. (Overriding the FilterOutputStream.write() method.)
You can print the output in output file by using FileOutputStream and PrintStream, You can try below code for better understanding.
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
java.io.File outFile = new java.io.File ("File name" );
FileOutputStream fos = new FileOutputStream(outFile);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
for(int i = 0 ; i < 5 ; i++) {
System.out.println(i);
}
}
}
This code prints the output in the text file, If the text file does not exist then it creates a new file and then prints output in the file.
I need to read from a file that contain 9000 words, what is the best way to read from this file and what is the difference between bufferingreader aND regular scanner.. or is there other good class to use?
Thanks
If you are doing "efficient" reading, there is no benefit to buffering. If, on the other hand, you are doing "inefficient" reading, then having a buffer will improve performance.
What do I mean by "efficient" reading? Efficient reading means reading bytes off of the InputStream / Reader as fast as they appear. Imagine you wanted to load a whole text file to display in an IDE or other editor. "inefficient" reading is when you are reading information off of the stream piecemeal - ie Scanner.nextDouble() is inefficient reading, as it reads in a few bytes (until the double's digits end), then transforms the number from text to binary. In this case, having a buffer improves performance, as the next call to nextDouble() will read out of the buffer (memory) instead of disk
If you have any questions on this, please ask
Open the file using an input stream. Then read its content to a string using this code:
public static void main(String args[]) throws IOException {
FileInputStream in = null;
in = new FileInputStream("input.txt");
String text = inputStreamToString(is);
}
// Reads an InputStream and converts it to a String.
public String inputStreamToString(InputStream stream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while((length = stream.read(buffer)) != -1)
byteArrayOutputStream.write(buffer,0,length);
return byteArrayOutputStream.toString("UTF-8");
}
Check this answer for comparisons between buffered readers:
Read/convert an InputStream to a String
I normally use Scanners when I want to read a file line by line, or based on a delimiter. For example:
try {
Scanner fileScanner = new Scanner(System.in);
File file = new File("file.txt");
fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
To scan based on a delimiter, you can use something similar to this:
fileScanner.userDelimiter("\\s"); // \s matches any whitespace
while(fileScanner.hasNext()){
//do something with scanned data
String word = fileScanner.next();
//Double num = fileScanner.nextDouble();
}
This question already has answers here:
How to Write text file Java
(8 answers)
Closed 6 years ago.
I have Come across so many programmes of how to read a text file using Scanner in Java. Following is some dummy code of Reading a text file in Java using Scanner:
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
But, please anyone help me in "Writing" some text (i.e. String or Integer type text) inside a .txt file using Scanner in java. I don't know how to write that code.
Scanner can't be used for writing purposes, only reading. I like to use a BufferedWriter to write to text files.
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();
Scanner is for reading purposes. You can use Writer class to write data to a file.
For Example:
Writer wr = new FileWriter("file name.txt");
wr.write(String.valueOf(2)) // write int
wr.write("Name"); // write string
wr.flush();
wr.close();
Hope this helps
I am trying the following code using the DataOutputStream. The OutputStream passed to the DataOutputStream is not printing anything. Please see my below code and pllease tell me anything wrong in this code.
public class DataStreamsExample {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the First Number");
int i = dis.readInt();
System.out.println("Enter the Second Numebr");
int j= dis.readInt();
int total = i+j;
DataOutputStream dos = new DataOutputStream(System.out);
dos.writeInt(total);
}
}
Why are you using data output streams? Can't you use a Scanner for reading input?
Calling dos.flush() will print out your result though.
OutputStream is fundamentally a binary construct. If you want to write text data (e.g. from the console) you should use a Writer of some description. To convert an OutputStream into a Writer, use OutputStreamWriter. Then create a PrintWriter around the Writer, and you can read a line using PrintWriter.println().
You can replace follow line
DataOutputStream out = new DataOutputStream(out);
into this
PrintWriter out = new PrintWriter(new OutputStreamWriter(out));
The character encoding can then be explicitly specified in the constructor of OutputStreamWriter.
I am writing a program that read string and integers from file, then copy the data and write to another file. Data entries should be separated by a space.
My input should and output should follow the following format, the first two set of numbers are string while the others are integers:
123123 242323 09 08 06 44
I get Exception in thread "main" java.util.NoSuchElementException when I run my code, I do not know why
import java.util.Scanner;
import java.io.*;
public class Billing {
public static void main(String[] args) throws IOException {
//define the variables
String callingnumber;
String callednumber;
String line;
int startinghour;
int startingminute;
int endinghour;
int endingminute;
//open input and output files
FileReader freader = new FileReader("BillingData.txt");
BufferedReader inFile = new BufferedReader(freader);
FileWriter fwriter = new FileWriter("BillingOutput.txt");
PrintWriter outFile = new PrintWriter (fwriter);
// set space between the numbers
line=inFile.readLine();
while(line!=null)
{
//creat a scanner to use space between the numbers
Scanner space = new Scanner(line).useDelimiter(" ");
callingnumber=space.next();
callednumber=space.next();
startinghour=space.nextInt();
startingminute=space.nextInt();
endinghour=space.nextInt();
endingminute=space.nextInt();
// writing data to file
outFile.printf("%s %s %d %d %d %d", callingnumber, callednumber,startinghour, startingminute, endinghour, endingminute);
line=inFile.readLine();
}//end while
//close the files
inFile.close();
outFile.close();
}//end of mine
}//end of class
I suspect that the scanner has run out of data in the line - probably because there are less than 6 values in it. To avoid the error you should do something like this:
if (space.hasNextInt()) {
startingHour = space.nextInt();
}
Your Scanner is trying to read in a token that either doesn't exist or is of the wrong type. Myself, I'd split the String, line using " " as my delimiter and then deal with the array returned.