I'm trying to write(and read) string to file using the "RandomAccessFile", but "fio.writeBytes(file1str)" adds the some garbage at the end of the string:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the D of planets: ");
file1str = in.readLine();
fio = new RandomAccessFile(new File("file1"), "rw");
fio.writeBytes(file1str);
System.out.println("Your enter: ");
for (String retval: file1str.split(",")) {
System.out.println(retval);
}
fio.close();
System.out.println("Data saves to 'file1'!");
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("Error1");
}
}
....But if we are open the file, we see additional 10700 at the end:
Sorry for my bad english
When you create a RandomAccessFile with mode = "rw", the documentation says "If the file does not already exist then an attempt will be made to create it."
This means that if the file already exists, then no attempt will be made to create it, delete it, truncate it, etc.
So, what is happening is that for whatever reason, you already have a "file1" which has 9 characters in it, and what your code does is that it only overwrites the first 4 characters. (The "5,10" part.)
Try deleting the file before writing to it, and everything should be fine.
Alternatively, consider the possibility that choosing a RandomAccessFile was a bad idea to begin with, and instead try using new BufferedWriter(new FileWriter(file)), to write a normal text file the normal way that normal people normally use.
Related
I have this code...
try{
FileReader fread = new FileReader(new File("testfile"));
int y = 0;
while (fread.ready()){
char path = (char)fread.read();
System.out.println(path);
if (path == '\n'){
y++;
}
}
System.out.println("Newlines: " + y);
}
catch (Exception e){
System.out.println(e.getMessage());
}
...and a file called testfile containing the following information...
ABC
...and when I run the program it prints out that the file contains one newline. Why is that? I simply cannot find the reason why, having read the Oracle documentation. My problem is easily solved by subtracting one from y, but I am not satisfied with that. This problem drives me crazy since I have no clue where the newline comes from.
(Posted on behalf of the OP).
My editor (and several else) was adding a newline after eof in the file. Here are pages that list different solutions for different editors:
https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-end-of-file-newline-char
Gedit adds line at end of file
I want to get multiple file by parsing a input file Through Java.
The Input file contains many fasta format of thousands of protein sequence and I want to generate raw format(i.e., without any comma semicolon and without any extra symbol like ">", "[", "]" etc) of each protein sequence.
A fasta sequence starts form ">" symbol followed by description of protein and then sequence of protein.
For example ► >lcl|NC_000001.10_cdsid_XP_003403591.1 [gene=LOC100652771]
[protein=hypothetical protein LOC100652771] [protein_id=XP_003403591.1] [location=join(12190..12227,12595..12721,13403..13639)]
MSESINFSHNLGQLLSPPRCVVMPGMPFPSIRSPELQKTTADLDHTLVSVPSVAESLHHPEITFLTAFCL
PSFTRSRPLPDRQLHHCLALCPSFALPAGDGVCHGPGLQGSCYKGETQESVESRVLPGPRHRH
Like above formate the input file contains 1000s of protein sequence. I have to generate thousands of raw file containing only individual protein sequence without any special symbol or gaps.
I have developed the code for it in Java but out put is : Cannot open a file followed by cannot find file.
Please help me to solve my problem.
Regards
Vijay Kumar Garg
Varanasi
Bharat (India)
The code is
/*Java code to convert FASTA format to a raw format*/
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.io.FileInputStream;
// java package for using regular expression
public class Arrayren
{
public static void main(String args[]) throws IOException
{
String a[]=new String[1000];
String b[][] =new String[1000][1000];
/*open the id file*/
try
{
File f = new File ("input.txt");
//opening the text document containing genbank ids
FileInputStream fis = new FileInputStream("input.txt");
//Reading the file contents through inputstream
BufferedInputStream bis = new BufferedInputStream(fis);
// Writing the contents to a buffered stream
DataInputStream dis = new DataInputStream(bis);
//Method for reading Java Standard data types
String inputline;
String line;
String separator = System.getProperty("line.separator");
// reads a line till next line operator is found
int i=0;
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline;
a[i]=a[i].replaceAll(separator,"");
//replaces unwanted patterns like /n with space
a[i]=a[i].trim();
// trims out if any space is available
a[i]=a[i]+".txt";
//takes the file name into an array
try
// to handle run time error
/*take the sequence in to an array*/
{
BufferedReader in = new BufferedReader (new FileReader(a[i]));
String inline = null;
int j=0;
while((inline=in.readLine()) != null)
{
j++;
b[i][j]=inline;
Pattern q=Pattern.compile(">");
//Compiling the regular expression
Matcher n=q.matcher(inline);
//creates the matcher for the above pattern
if(n.find())
{
/*appending the comment line*/
b[i][j]=b[i][j].replaceAll(">gi","");
//identify the pattern and replace it with a space
b[i][j]=b[i][j].replaceAll("[a-zA-Z]","");
b[i][j]=b[i][j].replaceAll("|","");
b[i][j]=b[i][j].replaceAll("\\d{1,15}","");
b[i][j]=b[i][j].replaceAll(".","");
b[i][j]=b[i][j].replaceAll("_","");
b[i][j]=b[i][j].replaceAll("\\(","");
b[i][j]=b[i][j].replaceAll("\\)","");
}
/*printing the sequence in to a text file*/
b[i][j]=b[i][j].replaceAll(separator,"");
b[i][j]=b[i][j].trim();
// trims out if any space is available
File create = new File(inputline+"R.txt");
try
{
if(!create.exists())
{
create.createNewFile();
// creates a new file
}
else
{
System.out.println("file already exists");
}
}
catch(IOException e)
// to catch the exception and print the error if cannot open a file
{
System.err.println("cannot create a file");
}
BufferedWriter outt = new BufferedWriter(new FileWriter(inputline+"R.txt", true));
outt.write(b[i][j]);
// printing the contents to a text file
outt.close();
// closing the text file
System.out.println(b[i][j]);
}
}
catch(Exception e)
{
System.out.println("cannot open a file");
}
}
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
}
}
If you provide me correct it will be much easier to understand.
This code will not win prices, due to missing java expertice. For instance I would expect OutOfMemory even if it is correct.
Best would be a rewrite. Nevertheless we all began small.
Give full path to file. Also on the output the directory is probably missing from the file.
Better use BufferedReader etc. i.o. DateInputStream.
Initialize i with -1. Better use for (int i = 0; i < a.length; ++i).
Best compile the Pattern outside the loop. But remove the Matcher. You can do if (s.contains(">") as well.
. One does not need to create a new file.
Code:
const String encoding = "Windows-1252"; // Or "UTF-8" or leave away.
File f = new File("C:/input.txt");
BufferedReader dis = new BufferedReader(new InputStreamReader(
new FileInputStream(f), encoding));
...
int i= -1; // So i++ starts with 0.
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline.trim();
//replaces unwanted patterns like /n with space
// Not needed a[i]=a[i].replaceAll(separator,"");
Your code contains the following two catch blocks:
catch(Exception e)
{
System.out.println("cannot open a file");
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
Both of these swallow the exception and print a generic "it didn't work" message, which tells you that the catch block was entered, but nothing more than that.
Exceptions often contain useful information that would help you track down where the real problem is. By ignoring them, you're making it much harder to diagnose your problem. Worse still, you're catching Exception, which is the superclass of a lot of exceptions, so these catch blocks are catching lots of different types of exceptions and ignoring them all.
The simplest way to get information out of an exception is to call its printStackTrace() method, which prints the exception type, exception message and stack trace. Add a call to this within both of these catch blocks, and that will help you see more clearly what exception is being thrown and from where.
I am creating a java console application and i need to use a notepad (txt) file to store PIN, AccountNo and Balance.
When the user enters the PIN (from BufferedReader) it should get validated from the notepad file and login to thge system. However, the code fragment which I used below only displays Enter PIN, and when i click on Enter, the program exits.
Could you please tell me what is the mistake which I have done here?
BufferedReader getIt = new BufferedReader(new InputStreamReader(System.in));
String userPIN = "";
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(
"D:\\Studies\\BCAS\\HND\\Semester 1\\Programming Concepts\\Assignment\\AccountInfo.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
System.out.println("Enter PIN");
userPIN = getIt.readLine();
while ((strLine = br.readLine()) != null) {
// Print the content on the console#
if (userPIN.equals(strLine)) {
System.out.println("You have login!");
}
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
There are quite a few reasons why the program can simply terminate, or appear to be successful in program execution (and hence terminate successfully without doing any useful work):
The contents of the file are read, but if the end of the stream has been reached, then the code simply does not handle the case gracefully (or even consider handling it). Specifically, the line while ((strLine = br.readLine()) != null) can result in a scenario where the body of the loop is not executed.
The else condition is absent inside the body of the while loop. If none of the entries provided by the user input match the contents of the file, the code does not handle the condition, and the result is ambiguous. For all practical purposes, it appears that login is successful if the provided PIN is not present in the file.
Avoid unnecessary decoration of Readers and Streams. BufferedReader in
= new BufferedReader(new FileReader("foo.in")); is sufficient to read character data from files, and it does provide the read and readline methods to use.
PS: It is recommended that you learn to program defensively, especially when dealing with files and streams. That would help isolating cases in your code that would result in ambiguious/vague conditions.
File.ReadAllLines would be more convenient in your case.. Wouldn't be wrong to introduce a user class either if your going the good ol' oop way.
If you want to do this by yourself, StreamReader (which takes FileInfo) is a good way to go. Try to create it by using the using statement (:)) which makes cleans up after your done.
I'm working on an assignment for school, and am trying something beyond for extra credit. The program is to demonstrate the efficiency differences between a linear & binary search for a given array size of integers. I have a loop set up that creates an int[size] array, searches for a random number, then creates a new array of int[size*2].
The results are then written to a text file. The output writes fine, but after compiling & running the program several times, the output file has that many sections of data.
This is my code that is nested inside a try/catch block:
File output= new File("c:\\BigOhResults.txt");
int counter=2;
if (output.canWrite() && output.exists()) {
BufferedWriter out= new BufferedWriter(new FileWriter(output, true));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
}
Is there any way I can erase the text within that output file upon each time the program is run?
the reason I'm doing this is the professor requires the result printout with the data graphed. I have already completed the graphing requirement, and it works fine. I just want to have the file printout match the graph printout.
The second argument to the FileWriter constructor, which you're passing in "true", is "append". I.e. because you've set it to true, it will append your new output to the end of the file. If you pass in false instead, it will wipe the data that's there already and write it new.
Read the documentation for FileWriter. You do not want to append.
As already mentioned, the [FileWriter][1] constructor allows you to specify to clear the existing text and start at the beginning of the file. Some other remarks about the code:
The check on output.exists() is redundant after a call to output.canWrite() and isn't needed. output.canWrite() will check if the file exists and that you can write to it.
Don't forget to close the BufferedWriter object.
Like so:
if (output.canWrite()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output, false));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
} catch (IOException e) {
// Do what you want here, print a message or something
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
// Again, do what you want here
}
}
}
}
[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
Okay so I tried something and it worked. This is when you have a file that is intended to append any new text, but you want to reset/erase the contents of the file at the beginning of program execution. Hope I made sense.
PrintWriter pw1 = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt")));
pw1.close(); // Make sure the first PrintWriter object name is different from the second one.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt", true))); // PrintWriter in append-mode. When you recreate the text file with the same name, the file contents are erased because the previous object was not in append mode.
pw.close();
I want to read a file in java. And then, I want to delete a line from that file without the file being re-written.
How can I do this?
Someone suggested me to read/write to a file without the file being re-written with the help of RandomAccessFile. How to write data to a file through java?
Specifically, that files contains lines. One line contains three field - id, name and profession - separated by \t. I want to read that file through a Reader or InputStream or any other way and then search for a line that has the specified keyword (say 121) and then wants to delete that whole line.
This operation needs to be performed without the whole file being re-written
I don't think you can alter a file on a filesystem in any way without writing to it, including deleting a line.
Do you mean you want to write the file without altering the file's metadata, like the last modified time?
Based on your updated question:
I don't think you can do what you're asking to do here. You can't remove bytes from a file once the file has been written, note no deleteByte or removeByte methods in RandomAccessFile.
I suggest moving the content of your file to a database - that allows this kind of record-oriented operation.
The alternative is, you have to rewrite the file. Sorry!
"Lines" are an abstract concept -- they're just an arbitrary sequence of bytes terminated by "\n". BufferedWriters and their ilk don't support textual editing in this way, so you'll have to rewrite the file in its entirety.
In general, what you want to do is:
open a reader
read content into some suitable data structure
close the reader
change data/records which need to be changed in this data structure
open a FileWriter with append == false
write content of data structure to resulting file
close FileWriter
add a marker in your lines saying if your line is deleted or not : this will make a software delete instead od a hardware delete.
if you have to insert new lines, you then can reuse those that are marked as deleted.
The below code searchs the line or fields in a single text file reads the file line by line
then the line or fields can be replaced by " " or any other string. Here we use the pattern and Matcher classes.
If this not clearing your question do let me know.
import java.io.;
import java.util.regex.;
import java.util.Properties;
public class DeleteLine
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String line=null;
File f = new File("d:/xyz.txt");
String replaceString=properties.getProperty("replaceAll.String");
;
br = new BufferedReader(new FileReader("d:/giri/scjp/");
while ( (line = br.readLine()) != null )//BufferedReader contains readline method
{
Pattern p=Pattern.compile(searchString);/*here u an specify the line u want to delete */
Matcher m=p.matcher(line);
line=m.replaceAll(replaceString);/*here replace String u can " " so that it will be emptied */
System.out.println(line);
}
//System.out.println(line);
}
}
}
br = new BufferedReader(new FileReader("d:/xyz.txt"));
String line = null;
}
catch (FileNotFoundException e)
{
System.out.println("File couldnt find");
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}