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 :)
Related
So this is a function I created.
As you can see this will read for files searching for filename and then it reads for --TEMPERATURE UP--.
Problem is not every filename has a --TEMPERATURE UP-- and
I tried using an else statement but if I remove the break from the else statement, for filename without --TEMPERATURE UP-- the whole app will crash
But if I add a break statement in the else statement, every filename will run the else statement which even if they contains --TEMPERATURE UP--
I have also tried to do a simple else statement without the !line.equals("--TEMPERATURE UP--") but it's still the same.
Either I have to add break at the else to run the else code which will not run the if code OR I remove the break which run the if code but unable to run the else code as it will crash.
Please advise on how I should go about changing my codes such that when it reads --TEMPERATURE UP-- it will run the if code, otherwise it will run the else code.
Thanks alot.
public void tempUp() {
SharedPreferences sharedTest = getSharedPreferences("MySharedTest", Context.MODE_PRIVATE);
String filename = sharedTest.getString("filename", " ");
Log.d("File readed: ", filename);
File dir = new File(path);
File[] files = dir.listFiles();
for (File f : files) {
if (f.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(f));
String lineToRead = filename;
String CurrentLine;
while ((CurrentLine = inputStream.readLine()) != null) {
if (CurrentLine.equals(lineToRead)) {
try
{
BufferedReader reader = new BufferedReader(new FileReader(f));
String line = reader.readLine();
while(line !=null)
{
line = reader.readLine();
if(line.equals("--TEMPERATURE UP--"))
{
final String ms = reader.readLine();
Log.d("temp up: ", ms);
new Thread(new Runnable()
{
#Override
public void run()
{
String message = "\u000704NTX" + ms + "\r";
byte[] byte_array = message.getBytes();
try
{
SharedPreferences prefx = getSharedPreferences("Device_Data", Context.MODE_PRIVATE);
String device_ip = prefx.getString("local_ip", " ");
String host = device_ip;
Socket socket = new Socket(host, 8070);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(byte_array);
out.flush();
}
catch (Exception e)
{
}
}
}).start();
break;
}
else if (!line.equals("--TEMPERATURE UP--"))
{
Toast.makeText(TestScreen.this, "There is no Temperature Display for this profile.", Toast.LENGTH_LONG).show();
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Updated:
try
{
BufferedReader reader = new BufferedReader(new FileReader(f));
String line = reader.readLine();
boolean hasTempDisplayProfile = false;
while((line = reader.readLine()) !=null)
{
if(line.equals("--TEMPERATURE UP--")) {
hasTempDisplayProfile = true;
final String ms = reader.readLine();
Log.d("temp up: ", ms);
new Thread(new Runnable() {
#Override
public void run() {
String message = "\u000704NTX" + ms + "\r";
byte[] byte_array = message.getBytes();
try {
SharedPreferences prefx = getSharedPreferences("Device_Data", Context.MODE_PRIVATE);
String device_ip = prefx.getString("local_ip", " ");
String host = device_ip;
Socket socket = new Socket(host, 8070);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(byte_array);
out.flush();
} catch (Exception e) {
}
}
}).start();
break;
}
}
if (hasTempDisplayProfile){
Toast.makeText(TestScreen.this, "There is no Temperature Display for this profile.", Toast.LENGTH_LONG).show();
break;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Your current implementation is:
while(readLine) {
if (line.equal("--TEMPERATURE UP--") {
// process
} else {
// Toast message
}
}
So do you see the problem now? The problem is your are testing again --TEMPERATURE UP-- for every line and show Toast every time the line is not match.
It's wrong.
What you want is to check if the whole file does not contain the --TEMPERATURE UP--, if so, then show the toast.
So the correct implementation would involving a flag:
boolean hasTempDisplayProfile = false;
while(readLine) {
if (line.equal("--TEMPERATURE UP--") {
// process
hasTempDisplayProfile = true;
}
}
if (!hasTempDisplayProfile) {
// Toast message
}
Edit
Your code has another serious flaw:
String line = reader.readLine();
while(line !=null){
line = reader.readLine();
... your process ...
}
In this code, you read a line. Then check for line not equals null in the while. The problem is you did not use that line but process to read another line = reader.readLine(). It will throw NullPointerException when you reach end of file.
Change to this:
String line;
while((line = reader.readLine()) !=null){
// Do not read new line here. Just process with "line"
}
By the way, your code need improvement. It now has too much indentation, which is very frustrate to read. You can try:
Break your function into smaller modules
Use fail-fast. That is instead of wrap your code if the condition hold true, try to return when false. For example your:
for (File f: files) {
if (f.isFile()) {
// Your process
}
}
should be changed to:
for (File f: files) {
if (!f.isFile()) {
continue;
}
// Your process
}
It reduces one level of indentation.
I am trying to duplicate the original into a new file. In the new file I want the exact same things as the original BUT no blank lines.
Note: I looked at other posts and tried with no success.
Currently:
1
2
3
How I want it to be: -- no blank lines
1
2
3
Here is my code so far:
inputFileName = "x.txt";
outputFileName = "y.txt";
inputFile = new BufferedReader(new FileReader(inputFileName));
outputFile = new PrintWriter(new FileWriter(outputFileName));
String lineOfText = inputFile.readLine();
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
inputFile.close();
outputFile.close();
}
Thank you for all who can possibly help. I assumed that print("null") would print out 'nothing' but it indeed prints out null, I do not know how to print out 'nothing'.
You need to skip the println in case the line is empty:
while(lineOfText != null)
{
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
You're on the right track, but this
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
shouldn't be writing null on empty lines. I think you wanted something like
while(lineOfText != null)
{
if (!lineOfText.isEmpty())
{
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
Also, I suggest you use a try-with-resources Statement instead of manually managing your close(s). It's probably a good idea to trim (as suggested in the comments) before your test, and you can simplify your loop and you should limit variable visibility. All together like,
String inputFileName = "x.txt";
String outputFileName = "y.txt";
try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName))) {
String lineOfText;
while ((lineOfText = inputFile.readLine()) != null) {
lineOfText = lineOfText.trim();
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
}
}
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data1.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm trying to read in a .csv file containing node data (p-values mostly) into my progam, but in doing so I have to convert them from strings into doubles. Here's the method for it:
public ArrayList<Node> getCSVFile(String file){
String csvFile = file;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Node> nL = new ArrayList<Node>();
int count = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] node = line.split(cvsSplitBy);
double pVal = Double.parseDouble(node[4]);
nL.add(new Node(count, node[0], pVal));
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nL;
}
The object Node is parameterized as Node(int, String, double), but the first line of the file I'm trying to convert is a column name, and I'm not entirely sure of the nature of the entries after that. Here's a look at the start of the file:
GENE,COMMON,gal1RGexp,gal4RGexp,gal80Rexp,gal1RGsig,gal4RGsig,gal80Rsig
YHR051W,COX6,-0.034,0.111,-0.304,3.75720e-01,1.56240e-02,7.91340e-06
YHR124W,NDT80,-0.090,0.007,-0.348,2.71460e-01,9.64330e-01,3.44760e-01
YKL181W,PRS1,-0.167,-0.233,0.112,6.27120e-03,7.89400e-04,1.44060e-01
YGR072W,UPF3,0.245,-0.471,0.787,4.10450e-04,7.51780e-04,1.37130e-05
YHL020C,OPI1,0.174,-0.015,0.151,1.40160e-04,7.19120e-01,1.53950e-02
YGR145W,YGR145W,0.387,-0.577,-0.088,5.37920e-03,8.27330e-03,7.64180e-01
YGL041C,YGL041C,0.285,-0.086,0.103,4.46050e-04,4.50790e-01,7.03040e-01
YGR218W,CRM1,-0.018,-0.001,-0.018,6.13810e-01,9.79400e-01,8.09690e-01
YOR202W,HIS3,-0.432,-0.710,0.239,1.09790e-02,1.79790e-04,5.48950e-03
YCR005C,CIT2,0.085,0.392,0.464,4.18980e-02,1.53050e-06,2.74360e-06
YER187W,KHS1,0.159,0.139,-0.045,8.51260e-04,4.17830e-03,6.18020e-01
YBR026C,YBR026C,0.276,0.189,0.291,3.63320e-05,6.15230e-04,1.24430e-03
YMR244W,YMR244W,0.078,-0.239,-0.072,5.76050e-01,3.55240e-01,8.85690e-01
Etc etc..
So the code creates nodes for each line based on the first and fifth columns, as well as a unique counter. However how can I skip the first line that just has the column names? I'm a little hesitant to simply have something skipping all first lines in all files, as not all files read may have a string as a first line. Even then, are the following lines suitable for being converted to doubles?
Thanks!
What about skipping lines when parsing the double is not possible?
Like this:
public ArrayList<Node> getCSVFile(String file){
String csvFile = file;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Node> nL = new ArrayList<Node>();
int count = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] node = line.split(cvsSplitBy);
double pVal;
try {
pVal = Double.parseDouble(node[4]);
} catch (NumberFormatException e) {
continue; // Skip this line if this isn't a double
}
nL.add(new Node(count, node[0], pVal));
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nL;
}
Change the signature of your existing method to:
public ArrayList<Node> getCSVFile(String file, int startAt){
and use startAt inside of your read loop to control how many lines are skipped. I'd recommend creating a default method that returns all lines:
public ArrayList<Node> getCSVFile(String file){
return getCSVFile(file, 0);
}
Alternatively this could be a boolean if you know that you'll either want to skip the first line or none at all.
As for the second part of your question, many of those strings will not be parseable. You may want to read this. But I'm not sure how you expect to parse or use a value like 'YHR051W' (since you said you wanted the first column).
I am trying to simply read in a line from a text file using BufferedReader. Here is the sample code:
try {
BufferedReader reader = new BufferedReader( new FileReader( "data.txt") );
while(reader.readLine() != null )
{
System.out.println(reader.readLine())
}
}
} catch (Exception e) {
e.printStackTrace();
}
The code above seems to not only print out null, but sets the data.txt file to null (as in, the file data.txt would initially have 40kb, and a call to readLine() sets it to 0kb)?
I have no idea why this is occurring, it can locate the file, but sets the file to null?
Can anyone identify why this is occurring?
Thanks.
EDIT !!
The BufferedWriter code is below:
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))
for(int x=0; x<64; x++)
{
writer.write(String.valueOf(data[x]));
}
writer.newLine();
writer.newLine();
}
catch(IOException io)
{};
Not sure why your file contents gets erased however you need to change your while loop to this since you're skipping lines if you use your code.
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Your first readline() is used as while loop condition. Then you write the second readline() to System.out. So you're writing every 2nd line. What you need is this.
String str = null;
while((str=reader.readLine()) != null) {
System.out.println(str);
}
You are printing every second line only, and may also print the end of file null terminator. This is because the while conditional reads the line from your file as well, and that you simply discard this line after checking against null.
Retain the line value in the variable:
String s;
while( (s = reader.readLine()) != null )
{
System.out.println(s);
}
Here's a working sample, similar to your original. Note that closing resources is very important:
import java.io.*;
import java.util.*;
public class ReadFile
{
public static final void main(String[] argv)
{
String fileName="data-2.txt";
writeFile(fileName);
readFile(fileName);
}
private static void writeFile(String fileName)
{
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(fileName));
for(int x=0; x<64; x++)
{
writer.write("some data\n");
}
writer.newLine();
writer.newLine();
}
catch(IOException x)
{
x.printStackTrace();
}
finally
{
safeClose(writer);
}
}
private static void readFile(String fileName)
{
BufferedReader reader = null;
String line = null;
try
{
reader = new BufferedReader( new FileReader( fileName ));
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException x)
{
x.printStackTrace();
}
finally
{
safeClose(reader);
}
}
private static void safeClose(Closeable closeable)
{
if(null != closeable)
{
try
{
closeable.close();
}
catch(IOException x)
{
//ignore -x.printStackTrace()
}
}
}
}
you are reading one line in while loop and then again reading next line in println statement. that means you are when you check the condition that time reader.readLine() does not equal to null, but when you read in println then it become null .`
while(reader.readLine() != null )
{
System.out.println(reader.readLine())
}
you should write your code in this way:
String line = null;
while((line=reader.readLine()) != null)
{
System.out.println(line) ;
}
did you close your writer object? you should close your writer object inside finally block this way.
this might help you to resolve your problem.
finally
{
if(null != writer)
{
try
{
writer.close();
}
catch(IOException ioException)
{
}
}
}
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);
}
}
}
}