Making Java I / O and change the file to split in java - java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)

I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Access external files

Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}

String and Text File Match Very basic

So i have recently dove head first into java trying to learn lots of things. Recently i have been studying File Writers and Reader and Buffered Writers and Readers. I have recently came to a haul though every time i turn on the application the text file is modified agian. Is there a way that my text file can update every time i change a string. So basically it will read the file on boot and compare it to the string.
Here is my example of reading a text file and turning it into a string
private void Read() {
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch(IOException e) {
e.printStackTrace();
}
}
All i need to do is it to compare this string with another. Thank you for your time.
** Update**
So i compared the two threads and now nothing is being written to the text file
private void Update() {
try {
fw= new FileWriter(version.getAbsoluteFile());
bw = new BufferedWriter(fw);
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
if(!sCurrentLine.equals(VanoEngine.TITLE)) {
bw.write(VanoEngine.TITLE);
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
** Update**
Closed the stream #JavaNoob and still nothing is being written
private void Update() {
try {
fw= new FileWriter(version.getAbsoluteFile());
bw = new BufferedWriter(fw);
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
if(!sCurrentLine.equals(VanoEngine.TITLE)) {
bw.write(VanoEngine.TITLE);
}
}
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
if(!sCurrentLine.equals(someInputString))
//write `someInputString` to file, because it differs with the one read from file
you can use sCurrentLine.equals("your string").

Writing to a file in Java. Help me code

I am passing a file path to this method which writes the in txt file. But when I run this program it is not writing full and I don't know where I made mistake.
public void content(String s) {
try {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
String read=s;
while((read = br.readLine()) != null) {
PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
out.write(read);
out.close();
}
} catch(Exception e) { }
} catch(Exception e) { }
}
You shouldn't create your PrintWriter inside the loop every time:
public void content(String s) {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
String read=null;
while((read=br.readLine())!=null) {
out.write(read);
}
} catch(Exception e) {
//do something meaningfull}
} finally {
out.close();
}
}
Aditionally, as others have mentioned add a finally block, do not silently catch the exception, and follow the Java Coding Conventions.
close your PrintWriter inside finally block out side the loop
finally {
out.close();
}
It's better to use Apache Commons IO instead.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html should make the trick.
(Unless you are trying to learn the low-level stuff or actually knows why you can't use IOUtils for this case.)
try this
public void content(String s) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(s));
PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
for (String line; (line = br.readLine()) != null;) {
pr.println(line);
}
}
}
Your closing stream before finishing it. So either put it into
<code>
finally {
out.close();
}
</code>
or see this simple example
<code>try {
String content = s;
File file = new File("/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
</code>

Why does the integer written to a file get read as a different value?

I've got a program where I need to generate an integer, write it to a text file and read it back the next time the program runs. After some anomalous behavior, I've stripped it down to setting an integer value, writing it to a file and reading it back for debugging.
totScore, is set to 25 and when I print to the console prior to writing to the file, I see a value of 25. However, when I read the file and print to the console I get three values...25, 13, and 10. Viewing the text file in notepad gives me a character not on the keyboard, so I suspect that the file is being stored in something other that int.
Why do I get different results from my write and read steps?
Is it not being written as an int? How are these values being stored in the file? Do I need to cast the read value as something else and convert it to an integer?
Consider:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.nio.file.StandardOpenOption.*;
//
public class HedgeScore {
public static void main(String[] args) {
int totScore = 25;
OutputStream outStream = null; ///write
try {
System.out.println("totscore="+totScore);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hedgescore.txt")));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
bw.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
try {
InputStream input = new FileInputStream("hedgescore.txt");
int data = input.read();
while(data != -1) {
System.out.println("data being read from file :"+ data);
data = input.read();
int prevScore = data;
}
input.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
}
}
You're reading/writing Strings and raw data, but not being consistent. Why not instead read in Strings (using a Reader of some sort) and then convert to int by parsing the String? Either that or write out your data as bytes and read it in as bytes -- although that can get quite tricky if the file must deal with different types of data.
So either:
import java.io.*;
public class HedgeScore {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
BufferedWriter bw = null;
try {
System.out.println("totscore=" + totScore);
bw = new BufferedWriter(new FileWriter(new File(
FILE_PATH)));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream input = null;
try {
input = new FileInputStream(FILE_PATH);
int data = 0;
while ((data = input.read()) != -1) {
System.out.println("data being read from file :" + data);
}
input.close();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
or:
import java.io.*;
public class HedgeScore2 {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
PrintWriter pw = null;
try {
System.out.println("totscore=" + totScore);
pw = new PrintWriter(new FileWriter(new File(FILE_PATH)));
pw.write(String.valueOf(totScore));
pw.write(System.getProperty("line.separator"));
pw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (pw != null) {
pw.close();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

read multiple data in multiple files

I have a list of files in the directory C:\Users\Mahady\Desktop\Java 31122011\src\register\
they are like this....
100100545.txt
100545454.txt etc etc
in each file, file data are like this line by line:
Bob
1234
4834
London
9852
1
My question is, how do i read each files one by one in the directory and for each files read all lines except line 3. i would then like to merge this data in word and create letters. thanks
Detailed Answer....
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line = null;
int lineCount = 0;
while (null != (line = bufferedReader.readLine())) {
lineCount++;
if (3 != lineCount) {
System.out.println(line);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hope this would help you.
Try this:
File dir = new File("C:\\Users\\Mahady\\Desktop\\Java 31122011\\src\\register\\");
for (string fn : dir.list()) {
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}
Obviously, you will need to add exception handling code around this skeletal implementation.

Categories