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--;
}
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 used to the c-style getchar(), but it seems like there is nothing comparable for java. I am building a lexical analyzer, and I need to read in the input character by character.
I know I can use the scanner to scan in a token or line and parse through the token char-by-char, but that seems unwieldy for strings spanning multiple lines. Is there a way to just get the next character from the input buffer in Java, or should I just plug away with the Scanner class?
The input is a file, not the keyboard.
Use Reader.read(). A return value of -1 means end of stream; else, cast to char.
This code reads character data from a list of file arguments:
public class CharacterHandler {
//Java 7 source level
public static void main(String[] args) throws IOException {
// replace this with a known encoding if possible
Charset encoding = Charset.defaultCharset();
for (String filename : args) {
File file = new File(filename);
handleFile(file, encoding);
}
}
private static void handleFile(File file, Charset encoding)
throws IOException {
try (InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
// buffer for efficiency
Reader buffer = new BufferedReader(reader)) {
handleCharacters(buffer);
}
}
private static void handleCharacters(Reader reader)
throws IOException {
int r;
while ((r = reader.read()) != -1) {
char ch = (char) r;
System.out.println("Do something with " + ch);
}
}
}
The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charset class for more. (If you feel masochistic, you can read this guide to character encoding.)
(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Character class for more details; this is an edge case that probably won't apply to homework.)
Combining the recommendations from others for specifying a character encoding and buffering the input, here's what I think is a pretty complete answer.
Assuming you have a File object representing the file you want to read:
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
// Do something with your character
}
Another option is to not read things in character by character -- read the entire file into memory. This is useful if you need to look at the characters more than once. One trivial way to do that is:
/** Read the contents of a file into a string buffer */
public static void readFile(File file, StringBuffer buf)
throws IOException
{
FileReader fr = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
char[] cbuf = new char[(int) file.length()];
br.read(cbuf);
buf.append(cbuf);
br.close();
}
finally {
if (fr != null) {
fr.close();
}
}
}
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
You have several options if you use BufferedReader. This buffered reader is faster than Reader so you can wrap it.
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
Wrap your reader in a BufferedReader, which maintains a buffer allowing for much faster reads overall. You can then use read() to read a single character (which you'll need to cast). You can also use readLine() to fetch an entire line and then break that into individual characters. The BufferedReader also supports marking and returning, so if you need to, you can read a line multiple times.
Generally speaking, you want to use a BufferedReader or BufferedInputStream
on top of whatever stream you are actually using since the buffer they maintain will make multiple reads much faster.
In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.
for instance;
for use Scanner method import java.util.Scanner;
after in main method:define
Scanner myScanner = new Scanner(System.in);
//for read character
char anything=myScanner.findInLine(".").charAt(0);
you anything store single character, if you want more read more character declare more object like anything1,anything2...
more example for your answer please check in your hand(copy/paste)
import java.util.Scanner;
class ReverseWord {
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
char c1,c2,c3,c4;
c1 = myScanner.findInLine(".").charAt(0);
c2 = myScanner.findInLine(".").charAt(0);
c3 = myScanner.findInLine(".").charAt(0);
c4 = myScanner.findInLine(".").charAt(0);
System.out.print(c4);
System.out.print(c3);
System.out.print(c2);
System.out.print(c1);
System.out.println();
}
}
This will print 1 character per line from the file.
try {
FileInputStream inputStream = new FileInputStream(theFile);
while (inputStream.available() > 0) {
inputData = inputStream.read();
System.out.println((char) inputData);
}
inputStream.close();
} catch (IOException ioe) {
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
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");
}
}
}
I have a text file with the following contents:
one
two
three
four
I want to access the string "three" by its position in the text file in Java.I found the substring concept on google but unable to use it.
so far I am able to read the file contents:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I want to apply the substring concept to the file.It asks for the position and displays the string.
String Str = new String("Welcome to Tutorialspoint.com");
System.out.println(Str.substring(10, 15) );
If you know the byte offsets within the file that you are interested in then it's straightforward:
RandomAccessFile raFile = new RandomAccessFile("textfile.txt", "r");
raFile.seek(startOffset);
byte[] bytes = new byte[length];
raFile.readFully(bytes);
raFile.close();
String str = new String(bytes, "Windows-1252"); // or whatever encoding
But for this to work you have to use byte offsets, not character offsets - if the file is encoded in a variable-width encoding such as UTF-8 then there's no way to seek directly to the nth character, you have to start at the top of the file and read and discard the first n-1 characters.
look for \r\n (linebreaks) in your text file. This way you should be able to count the rows containing your string.
your file in reality looks like this
one\r\n
two\r\n
three\r\n
four\r\n
You seem to be looking for this. The code I posted there works on the byte level, so it may not work for you. Another option is to use the BufferedReader and just read a single character in a loop like this:
String getString(String fileName, int start, int end) throws IOException {
int len = end - start;
if (len <= 0) {
throw new IllegalArgumentException("Length of string to output is zero or negative.");
}
char[] buffer = new char[len];
BufferedReader reader = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < start; i++) {
reader.read(); // Ignore the result
}
reader.read(buffer, 0, len);
return new String(buffer);
}
I am used to the c-style getchar(), but it seems like there is nothing comparable for java. I am building a lexical analyzer, and I need to read in the input character by character.
I know I can use the scanner to scan in a token or line and parse through the token char-by-char, but that seems unwieldy for strings spanning multiple lines. Is there a way to just get the next character from the input buffer in Java, or should I just plug away with the Scanner class?
The input is a file, not the keyboard.
Use Reader.read(). A return value of -1 means end of stream; else, cast to char.
This code reads character data from a list of file arguments:
public class CharacterHandler {
//Java 7 source level
public static void main(String[] args) throws IOException {
// replace this with a known encoding if possible
Charset encoding = Charset.defaultCharset();
for (String filename : args) {
File file = new File(filename);
handleFile(file, encoding);
}
}
private static void handleFile(File file, Charset encoding)
throws IOException {
try (InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
// buffer for efficiency
Reader buffer = new BufferedReader(reader)) {
handleCharacters(buffer);
}
}
private static void handleCharacters(Reader reader)
throws IOException {
int r;
while ((r = reader.read()) != -1) {
char ch = (char) r;
System.out.println("Do something with " + ch);
}
}
}
The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charset class for more. (If you feel masochistic, you can read this guide to character encoding.)
(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Character class for more details; this is an edge case that probably won't apply to homework.)
Combining the recommendations from others for specifying a character encoding and buffering the input, here's what I think is a pretty complete answer.
Assuming you have a File object representing the file you want to read:
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
// Do something with your character
}
Another option is to not read things in character by character -- read the entire file into memory. This is useful if you need to look at the characters more than once. One trivial way to do that is:
/** Read the contents of a file into a string buffer */
public static void readFile(File file, StringBuffer buf)
throws IOException
{
FileReader fr = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
char[] cbuf = new char[(int) file.length()];
br.read(cbuf);
buf.append(cbuf);
br.close();
}
finally {
if (fr != null) {
fr.close();
}
}
}
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
You have several options if you use BufferedReader. This buffered reader is faster than Reader so you can wrap it.
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
Wrap your reader in a BufferedReader, which maintains a buffer allowing for much faster reads overall. You can then use read() to read a single character (which you'll need to cast). You can also use readLine() to fetch an entire line and then break that into individual characters. The BufferedReader also supports marking and returning, so if you need to, you can read a line multiple times.
Generally speaking, you want to use a BufferedReader or BufferedInputStream
on top of whatever stream you are actually using since the buffer they maintain will make multiple reads much faster.
In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.
for instance;
for use Scanner method import java.util.Scanner;
after in main method:define
Scanner myScanner = new Scanner(System.in);
//for read character
char anything=myScanner.findInLine(".").charAt(0);
you anything store single character, if you want more read more character declare more object like anything1,anything2...
more example for your answer please check in your hand(copy/paste)
import java.util.Scanner;
class ReverseWord {
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
char c1,c2,c3,c4;
c1 = myScanner.findInLine(".").charAt(0);
c2 = myScanner.findInLine(".").charAt(0);
c3 = myScanner.findInLine(".").charAt(0);
c4 = myScanner.findInLine(".").charAt(0);
System.out.print(c4);
System.out.print(c3);
System.out.print(c2);
System.out.print(c1);
System.out.println();
}
}
This will print 1 character per line from the file.
try {
FileInputStream inputStream = new FileInputStream(theFile);
while (inputStream.available() > 0) {
inputData = inputStream.read();
System.out.println((char) inputData);
}
inputStream.close();
} catch (IOException ioe) {
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}