I have the following problem: I need to input a file with 12 lines. Each line consist of 8 characters. I have to output it in a file with 8 lines and 12 characters. I have to read the input line by line and output each line at the same time. So I'm not allowed to read my input first and after i read it just cut in in 8 lines with 12 characters. I'm using BufferedReader to read my file and BufferedWriter to write to my file. So by example:
Input:
12345678
qwertyui
asdfghjk
Output:
12345678qwer
tyuiasdfghjk
Edit: It's an homework assignment indeed.
BufferedWriter bufferedWriter = null;
FileReader fr;
try {
fr = new FileReader(new File(directory to file));
bufferedWriter = new BufferedWriter(new FileWriter(directory to file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
bufferedWriter.write(output);
bufferedWriter.newLine();
line = br.readLine();
}
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
This is how i read my inputfile and write to an outputfile, and it's the code I have at the moment.
Use the read method of Reader class. (FileReader is a descendant of Reader).
I'm not going to implement the whole logic but here is a skeleton to work on.
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream =
new FileReader("inputfile.txt");
outputStream =
new FileWriter("outputfile.txt");
int c;
int counter = 1;
while ((c = inputStream.read()) != -1) {
//keep a counter that will cycle for 12 characters
//check if c represents a alphabet or number, write it to file else skip
//when counter is 12 write a newline
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
The read method allows you to control how many characters to read:
See BufferedReader#read.
Same with write
Related
I am using BufferedReader in java to read characters from an input file. However, the output is unusual. In my code below, I first use scanner to show the contents of the file itself then I use BufferedReader to print each individual character:
import java.util.Scanner;
import java.io.*;
//import java.io.File;
public class Inputs
{
public static void main(String[] args)
{
System.out.println("Inputs");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println(input);
// Open the file
File file = new File("Simple.java");
try {
Scanner fileIn = new Scanner(file);
while(fileIn.hasNext()){
System.out.println(fileIn.next());
}
fileIn.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// 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
String character = Character.toString ((char) br.read());
System.out.println (character);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Below is the output I get, the first tokens displayed are by the scanner but after the highlighted prentices its the BufferedReaders output. It prints 3 spaces then a closed curly bracket then -1 (end). What is the meaning of this?
In your code you are reading the line in while loop condition with br.readline(). Then in the loop body you are again reading the char using br.read(). So the first character in the each line is printed.
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}
To fix there either use the method metioned by Halko Sajtarevic(But there each char is read as an integer and converted back to string) or simply eliminate reading the character second time and just print the string.
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
Your problem is that you are reading the BufferedReader line by line instead of character by character.
Try this version instead:
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
char c;
while ((c = (char) br.read()) != (char) -1) {
// Print the content on the console
String character = Character.toString(c);
System.out.print(character);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
I'm required due to previous implementation to use an InputStream, I can't use a BufferedReader.
My test bench used a BufferedReader and a while loop, like so:
while ((line = br.readLine()) != null)
However br is now required to be an InputStream (and will be renamed). Is there any way of reading in this fashion with an InputStream, or do I have to read it bytes at a time and search for the \n?
If you must read with an InputStream, then wrap it into a InputStreamReader, and then wrap this in a BufferedReader, allowing you to use your familiar BufferedReader methods. There's no need to do non-buffered input in this situation.
// assuming that you have an InputStream named inputStream
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while((line = br.readLine()) != null) {
// use line here
}
} catch (IOException e) {
e.printStackTrace();
}
Or alternatively, wrap the InputStream in a Scanner object:
try (Scanner scanner = new Scanner(inputStream)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// use line here
}
}
You can change the code like this :
public String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r;
for (r = inputStream.read(); r != '\n' && r != -1 ; r = inputStream.read()) {
baos.write(r);
}
if (r == -1 && baos.size() == 0) {
return null;
}
String lines = baos.toString("UTF-8");
return lines;
}
Maybe this example helps you..
I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I have written the Java code to read from one file and write to a new file. The file from which I am reading has 5000 lines of records, but when I am writing to a new file I am able to write only between 4700-4900 records.
I think may be I am simultaneously reading from a file and writing to a file, which might be creating a problem.
My code is as follows:
Reading from a file:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
Writing to a file:
public void writeFile(String returnValue){
String newreturnValue = returnValue.replaceAll("[^0-9,]", "");
String delimiter = ",";
String newtext ="";
String[] temp;
temp = newreturnValue.split(delimiter);
FileWriter output = null;
try {
output = new FileWriter("/home/anand/Desktop/newinput.txt");
BufferedWriter writer = new BufferedWriter(output);
for(int i =0; i < temp.length ; i++){
writer.write("["+i+"] "+temp[i]);
writer.newLine();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
I need the suggestion to how to simultaneously read and write to a file.
You need to close writer instead of output. The BufferedWriter may not be writing all of the lines, and won't since you never close it.
You have to close the writer object. The last couple lines probably haven't been flushed onto the text file.
In addition, are you aware of the try-with-resource introduced in Java 7? You can condense your code to this by utilizing it:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename)) {
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
By doing this, Java will automatically close the reader object for you once the try block completes, regardless of whether or not an exception was thrown. This makes it easier to read your code :)
I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
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());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}