I am writing the length of the string into a file and the result is that value is being considered as ASCII value and the character specified with ASCII value is written in the file and then I try to read that character from with the help of FileInputStream and BufferInputStream and the result will not be displayed on the console. Why is the character from the file not printed to the console?
import java.io.*;
class Fileoutput{
public static void main(String args[])
{
try
{
File f=new File("C:\\Users\\parsh\\YG2108\\Testfile.txt");
FileInputStream fins=new FileInputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt");
FileOutputStream fouts=new FileOutputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt");
FileWriter bf=new FileWriter("C:\\Users\\parsh\\YG2108\\Testfile.txt");
BufferedInputStream fin=new BufferedInputStream(fins);
BufferedOutputStream fout=new BufferedOutputStream(fouts);
BufferedWriter bw=new BufferedWriter(bf);
int i;
String s1="Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc xdibnbnokcm knui9xkbmkl bv";
int length=s1.length(); //findin string length
System.out.println(length); //printing length on console
fout.write(length); //writting into the file
System.out.println("Sucess");
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
bw.close();
fout.close();
fin.close();
bf.close();
fouts.close();
fins.close();
System.out.println("All done");
}catch(Exception e){System.out.println(e);}
}
}
First See If The problem Is In The Way you Write inTo the File
Follow This Link How To Read From A File In Java and See This Link Also How to Write Into A File in Java
Problem Is not in The Asci Because if the Length of the String is int (As it should be )
You Should Parse it using Integer.tostring(length_of_the_string) before you write it into the File
instead of this line
fout.write(length);
write this line
fout.write(Integer.toString(length));
You can Google for your Problem Before Asking on Stackoverflow ( It Might be Solved Before On Stackoverflow )
Your code is mixing reading with writing - you have both reading objects and writing objects opened at the same time. Since you are using BufferedOutputStream output is not written directly to file (when buffer is not full) and you are reading file before it contains any data.
So to solve it, flush the output stream with fout.flush(); before reading, or ideally separate reading from writing:
import java.io.*;
class Fileoutput {
public static void main(String args[]) throws IOException {
File f = new File("test.txt");
f.createNewFile();
try (FileOutputStream fouts = new FileOutputStream(f); BufferedOutputStream fout = new BufferedOutputStream(fouts);) {
String s1 = "Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc xdibnbnokcm knui9xkbmkl bv";
int length = s1.length();
System.out.println(length);
fout.write(length);
//fout.flush(); //optional, everything is flushed when fout is closed
System.out.println("Sucess");
}
try (FileInputStream fins = new FileInputStream(f); BufferedInputStream fin = new BufferedInputStream(fins);) {
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
System.out.println("All done");
}
}
}
Related
I have this code:
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
zero("zero.out");
System.out.println(zeroRead("zero.out"));
}
public static String zeroRead(String name) {
try (FileInputStream fos = new FileInputStream(name);
BufferedInputStream bos = new BufferedInputStream(fos);
DataInputStream dos = new DataInputStream(bos)) {
StringBuffer inputLine = new StringBuffer();
String tmp;
String s = "";
while ((tmp = dos.readLine()) != null) {
inputLine.append(tmp);
System.out.println(tmp);
}
dos.close();
return s;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void zero(String name) {
File file = new File(name);
String text = "König" + "\t";
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos)) {
dos.write(text.getBytes(StandardCharsets.UTF_8));
dos.writeInt(50);
} catch (IOException e) {
e.printStackTrace();
}
}
}
zero() method writes data into file: the string is written in UTF-8, while the number is written in binary. zeroRead() read the data from file.
The file looks like this after zero() is executed:
This is what zeroRead() returns:
How do I read the real data König\t50 from the file?
DataInputStream's readLine method has javadoc that is almost yelling that it doesn't want to be used. You should heed this javadoc: That method is bad and you should not use it. It doesn't do charset encoding.
Your file format is impossible as stated: You have no idea when to stop reading the string and start reading the binary numbers. However, the way you've described things, it sounds like the string is terminated by a newline, so, the \n character.
There is no easy 'just make this filter-reader and call .nextLine on it available, as they tend to buffer. You can try this:
InputStreamReader isr = new InputStreamReader(bos, StandardCharsets.UTF_8);
However, basic readers do not have a readLine method, and if you wrap this in a BufferedReader, it may read past the end (the 'buffer' in that name is not just there for kicks). You'd have to handroll a method that fetches one character at a time, appending them to a stringbuilder, ending on a newline:
StringBuilder out = new StringBuilder();
for (int c = isr.read(); c != -1 && c != '\n'; c = isr.read())
out.append((char) c);
String line = out.toString();
will get the job done and won't read 'past' the newline and gobble up your binary number.
I am currently working a project and we have divided it in modules, in one of them, we have a file ( .exe ) extension. I decided to open it in binary format and read the contents of it, modify them. But, I am not to modify the changes and save it in the same file. When I am trying to do so, it says 0KB. It's working perfectly fine when using two files.
Here is the source code :
public static void main(String[] args) {
String strSourceFile="E:/e.exe";
String strDestinationFile="E:/f.exe";
try
{
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while( (noOfBytes = fin.read(b)) != -1 )
{
fout.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin.close();
fout.close();
Use RandomAccessFile or You can also create a new file with your changes save it and delete the original one. Once original file is deleted then rename this new file to the original one.
You are trying to read and write the same file with the input and the output stream so the file is not getting copied while you try to do it with the same file. Instead, use a middle file as the buffer, as in the below code I have used the f.exe as the middle buffer, next I have copied the data from the buffer file again to the original file jar.exe, at last you need to delete the buffer file.
Here is the below code :
String strSourceFile = "C:/jar.exe";
String strDestinationFile = "C:/f.exe";
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while ((noOfBytes = fin.read(b)) != -1) {
fout.write(b, 0, noOfBytes);
}
fin.close();
fout.close();
String strDestinationFile1 = "C:/jar.exe";
FileInputStream fin1 = new FileInputStream(strDestinationFile);
FileOutputStream fout1 = new FileOutputStream(strDestinationFile1);
while ((noOfBytes = fin1.read(b)) != -1) {
fout1.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin1.close();
fout1.close();
File file = new File("C:/f.exe");
file.delete();
I am trying to copy the content of one file to another using Java I/O Stream.
I have written below code for this, but it is copying only the last letter of the source file.
package io.file;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyTester {
public void copyFile() {
FileInputStream fis = null;
try{
fis = new FileInputStream("resources/Source.txt");
System.out.println("Started copying");
int data = fis.read();
while (data != -1){
try (FileOutputStream fos = new FileOutputStream("resources/Destination.docx")){
fos.write(data);
fos.close();
}
catch (IOException io) {
System.err.println("Error o/p:"+io.getMessage());
}
System.out.print((char)data+" ");
data = fis.read();
}
fis.close();
System.out.println("End Copying");
}
catch(IOException ioe){
System.err.println("ERROR: "+ioe.getMessage());
}
}
public static void main(String[] args) {
new FileCopyTester().copyFile();
}
}
In Source file I have data something like
22
/
7
3.142857
So in destination I am getting only
7
Kindly help If I am missing something in this, like something that should not overwrite the data in destination file.
You overwrite your file each time with one byte.
Solution: open the output stream outside your while loop, and close it afterwards.
Opening the stream at every turn of the loop is pointless - the new data is overwriting the old content of the file. However - opening the stream with the "append mode" will make your code work:
FileOutputStream fos = new FileOutputStream("resources/Destination.docx", true);
The second, nicer solution is to open the stream before loop:
FileInputStream fis = new FileInputStream("resources/Source.txt");
FileOutputStream fos = new FileOutputStream("resources/Destination.docx");
int data = fis.read();
while (data != -1){
fos.write(data);
data = fis.read();
}
fos.close();
I'm writing a java server and always read requests form the browser. For example, I have in browser http://localhost:8080/C:\Users\1\Desktop\tur.txt and read this request. Then saves a file path. Then I want to print the contents of the file to browser. For example, some text which is in tur.txt.
I'm doing it with a method in another class.
Here is a code of this class:
public class FileReader {
BufferedReader in;
File DataFile;
public void Reader(String directory, PrintStream out) throws IOException {
try {
File stockInputFile = new File(directory);
File StockOutputFile = new File(directory);
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count;
if (new File(directory).isDirectory()) {
directory=directory.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n"+
"Location: /"+directory+"/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f=new FileInputStream(directory);
// Determine the MIME type and print HTTP header
String mimeType="text/plain";
if (directory.endsWith(".html") || directory.endsWith(".htm"))
mimeType="text/html";
else if (directory.endsWith(".jpg") || directory.endsWith(".jpeg"))
mimeType="image/jpeg";
else if (directory.endsWith(".gif"))
mimeType="image/gif";
else if (directory.endsWith(".txt"))
mimeType="text/txt";
else if (directory.endsWith(".class"))
mimeType="application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n"+
"Content-type: "+mimeType+"\r\n\r\n");
System.out.println(mimeType);
// Send file contents to client, then close the connection
byte[] a=new byte[4096];
int n;
while ((n=f.read(a))>0)
out.write(a, 0, n);
// out.flush();
out.close();
}
catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n"+
"Content-type: text/html\r\n\r\n"+
"<html><head></head><body>"+directory+" not found</body></html>\n");
out.close();
}
}
}
It takes a directory to find a file a file on disk and PrintStream (PrintStream out = new PrintStream(new BufferedOutputStream(serSock.getOutputStream()));) to print the content to browser. But, the problem is that when I read this file. The content of this file removes. That means all that text that I had in tur.txt deletes. And the file becomes emtpty intead of beeng printed to the browser.
Can anyone explain why? Thank you.
The problem was here:
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
In FileOutputSteam. So when I deleted these 2 lines the program started to work correctly. I forgot that FileOutputStream clears all the data stored in the file.
I would like to thank #lamsomeone for his help.
I really not getting where the problem is.
I wanted to print the characters to a text file and im uisng printWriter to do the same.
if the file has a ";", i want to replace it with a new line and this is what im doing,
public static void downloadFile_txt(String sourceFilePathName, String contentType, String destFileName, HttpServletResponse response) throws IOException, ServletException
{
File file = new File(sourceFilePathName);
//FileInputStream fileIn = new FileInputStream(file);
FileReader fileIn = new FileReader(file);
long fileLen = file.length();
response.setContentType(contentType);
response.setContentLength((int)fileLen);
response.setHeader("Content-Disposition", String.valueOf((new StringBuffer("attachment;")).append("filename=").append(destFileName)));
PrintWriter pw = response.getWriter();
// Loop to read and write bytes.
int c=-1;
while ((c = fileIn.read()) != -1)
{
if(c!=59)
{
pw.print((char)c);
}
else
{
pw.println();
}
}
pw.flush();
pw=null;
fileIn.close();
}
But my file is priting everything except for the last character.
Eg.input =
:00004000,FFAD,2 Byte Ch;
:0000FFBD,FFBE,2 Byte Ch;
:0000FFBF,FFFF,2 Byte Ch;
output which im getting
:00004000,FFAD,2 Byte Ch
:0000FFBD,FFBE,2 Byte Ch
:0000FFBF,FFFF,2 Byte C
the last "h" is not getting printed.
Thanks in advance
A pw.flush(); might help you.
public class FlushPrintWriter {
public static void main(String[] args) throws IOException {
FileReader fileIn = new FileReader("in.txt");
FileWriter out = new FileWriter("out.txt");
PrintWriter pw = new PrintWriter(out);
int c;
while ((c = fileIn.read()) != -1) {
if(c!=59) {
pw.print((char)c);
} else {
pw.println();
}
}
pw.flush();
}
}
outputs
:00004000,FFAD,2 Byte Ch
:0000FFBD,FFBE,2 Byte Ch
:0000FFBF,FFFF,2 Byte Ch
as expected.
(Don't handle your IOExceptions like this - and close your readers and writers - this is for demonstration only!)
edit: now your code doesn't even compile (two vars called fileIn?)!
Even when run through the servlet code you're now mentioning, I can't reproduce your problem, and the output is as you would expect. So this is me giving up. I'm starting to suspect either the final ; isn't in your source file, or there is yet more processing your app is doing that you're not showing us.
Try flush() or close() your print writer.
And may be it is better to read line by line, replacing characters using String.replace()
Run the while loop upto file size
int fileSize=file.length();
while(fileSize>0)
{
//do your task of reading charcter and printing it or whatever you want
fileSize--;
}