I have written a method in Java to delete a caret at the end of each line of a file. The method is as follows:
//Creates a new file, and deletes the temp file
public void createFinalFile() throws FileNotFoundException, IOException{
// read file data into a String
String data1 = new Scanner(new File(fileDirectoryString + "tempFile.txt")).useDelimiter("\\Z").next();
// replace all ^ from end of line using (?m) - MULTILINE switch
data1 = data1.replaceAll("(?m)\\^$", "");
PrintWriter docketFile3 = new PrintWriter(new FileWriter(fileDirectoryString + "Forclosure-Docket-"+startingYear+startingMonth+startingDay+"-"+endingYear+endingMonth+endingDay+".txt", true));
docketFile3.write(data1);
}
The issue is that sometimes the temp file will have all the information, but after the method is run the newly created file is blank and I am not sure why. An example of the temp file is:
04/02/2014^BR-12-005193^09/12/2012^P1^SF^DEPOSIT AMOUNT PAID CUYAHOGA COUNTY SHERIFF^
04/02/2014^BR-12-005193^09/12/2012^P1^CS^COST PAYMENT $860.90 CUYAHOGA COUNTY SHERIFF^
While it should just delete the caret at the end of each line, it seems to be deleting every line.
Your regular expression is not what's doing this. Though the function overall reminds me more of this than anything else, it should work. The one thing though that could be going wrong is that you aren't closing your output file. Add docketFile3.close(); as a line after you write the data out.
Related
Basically, I have a jFrame where some data is supposed to show inside whenever I press a button. The data is being taken from different files and the way I want it to work is whenever I press the same button for a file to show me different lines, however it always shows the last line of the file. I would like to add that I am also using a Tokenizer, even though I'm not sure if it is relevant.
I've tried using loops and numbering the lines but it doesn't really work.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
//Stoke
//Protocol - 555
String fileName="Stoke.txt";
int lineNumber=0;
try
{
FileReader fin=new FileReader(fileName);
BufferedReader din=new BufferedReader(fin);
System.out.println("Data in the file "+fileName+" is ");
//read from the file
String line=null; //line of text
while((line=din.readLine())!=null && lineNumber<1){
//here we have read in a line of text
//now parase line to extract data and print it out to the screen
StringTokenizer st=new StringTokenizer(line,",");
String location=st.nextToken().trim();
String gps=st.nextToken().trim();
String humidity=st.nextToken().trim();
String temperature=st.nextToken().trim();
String dateNtime=st.nextToken().trim();
weatherTable.setText(location+"\n"+gps+"\n"+humidity+"\n"+temperature+"\n"+dateNtime+"\n");
}
din.close(); //close the stream
I am expecting the application to show different lines whenever i press jButton5 but it always shows the last line of the file.
You set lineNumber to 0 initially, and never update it...
but you use it in your while loop condition as lineNumber<1, which means the condition is never failing, until you reach the end of the file, where (line=din.readLine())!=null returns false, and you exit with the last line in the buffer.
You have to figure out a way to count lines, then randomize on [0..numberOfLines] if you want to ouput a random line only, or append instead of set on
weatherTable.setText(location+"\n"+gps+"\n"+humidity+"\n"+temperature+"\n"+dateNtime+"\n");
if you want the entire file to be set.
Im working on my code where I am importing two csv files and then parsing them
//Importing CSV File for betreuen
String filename = "betreuen_4.csv";
File file = new File(filename);
//Importing CSV File for lieferant
String filename1 = "lieferant.csv";
File file1 = new File(filename1);
I then proceed to parse them. For the first csv file everything works fine. The code is
try {
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
int PInummer = Integer.parseInt(values[1]);
String MNummer = values[0];
String KundenID = values[2];
//System.out.println(MNummer);
//create the caring object with the required paramaters
//Caring caring = new Caring(MNummer,PInummer,KundenID);
//betreuen.add(caring);
}
inputStream.close();
}catch(FileNotFoundException d) {
d.printStackTrace();
}
I then proceed to parse the other csv file the code is
// parsing csv file lieferant
try {
Scanner inputStream1 = new Scanner(file1);
while(inputStream1.hasNext()) {
String data1 = inputStream1.next();
String[] values1 = data1.split(",");
int LIDnummer = Integer.parseInt(values1[0]);
String citynames = values1[1];
System.out.println(LIDnummer);
String firmanames = values1[2];
//create the suppliers object with the required paramaters
//Suppliers suppliers = new
//Suppliers(LIDnummer,citynames,firmanames);
//lieferant.add(suppliers);
}
inputStream1.close();
}catch(FileNotFoundException d) {
d.printStackTrace();
}
the first error I get is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Verbindung.main(Verbindung.java:61)
So I look at my array which is firmaname at line 61 and I think, well it's impossible that its out of range since in my CSV file there are three columns and at index 2 (which I know is the third column in the CSV file) is my list of company names. I know the array is not empty because when i wrote
`System.out.println(firmanames)`
it would print out three of the first company names. So in order to see if there is something else causing the problem I commented line 61 out and I ran the code again. I get the following error
`Exception in thread "main" java.lang.NumberFormatException: For input
string: "Ridge"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Verbindung.main(Verbindung.java:58)`
I google these errors and you know it was saying im trying to parse something into an Integer which cannot be an integer, but the only thing that I am trying to parse into an Integer is the code
int LIDnummer = Integer.parseInt(values1[0]);
Which indeed is a column containing only Integers.
My second column is also indeed just a column of city names in the USA. The only thing with that column is that there are spaces in some town names like Middle brook but I don't think that would cause problems for a String type. Also in my company columns there are names like AT&T but i would think that the & symbol would also not cause problems for a string. I don't know where I am going wrong here.
I cant include the csv file but here is a pic of a part of it. The length of each column is a 1000.
A pic of the csv file
Scanner by default splits its input by whitespace (docs). Whitespace means spaces, tabs and newlines.
So your code will, I think, split the whole input file at every space and every newline, which is not what you want.
So, the first three elements your code will read are
5416499,Prairie
Ridge,NIKE
1765368,Edison,Cartier
I suggest using method readLine of BufferedReader then calling split on that.
The alternative is to explicitly tell Scanner how you want it to split the input
Scanner inputStream1 = new Scanner(file1).useDelimiter("\n");
but I think this is not the best use of Scanner when a simpler class (BufferedReader) will do.
First of all, I would highly suggest you try and use an existing CSV parser, for example this one.
But if you really want to use your own, you are going to need to do some simple debugging. I don't know how large your file is, but the symptoms you are describing lead me to believe that somewhere in the csv there may be a missing comma or an accidental escape character. You need to find out what line it is. So run this code and check its output before it crashes:
int line = 1;
try {
Scanner inputStream1 = new Scanner(file1);
while(inputStream1.hasNext()) {
String data1 = inputStream1.next();
String[] values1 = data1.split(",");
int LIDnummer = Integer.parseInt(values1[0]);
String citynames = values1[1];
System.out.println(LIDnummer);
String firmanames = values1[2];
line++;
}
} catch (ArrayIndexOutOfBoundsException e){
System.err.println("The issue in the csv is at line:" + line);
}
Once you find what line it is, the answer should be obvious. If not, post a picture of that line and we'll see...
So I'm trying to add text to a txt file, I have succeeded in doing this, the user is prompted about what they would like to add and it is included when I open the txt file after running my program.
Now, here's my problem: The first time I try to add something to the txt file, it creates a blank row and under that it will have the information the user has added, the reason for this is because when Java opens my file, the typing cursor is on the bottom of the last line, where there is no space and it is ready to enter information, like this:
Alright, cool, so this means whenever I add anything to the txt file from my Java program, it will automatically be on a new line and I will not need to add any println spacing to enter a new line. Now here's where another problem concurs, after Java puts the new text into the txt file, it leaves the typing cursor at the END of the new line added, not at the new line under it where there is no data. So this means if I try to add new information twice, it will appear on the same line and not a new one. So to fix this, I simply added a
pw.println();
statement at the start of my print writer to ensure it puts the cursor on the new line. But now, when i try to add data for the first time again after adding that last line of code, it will create a empty space between the last line of data and the new line of data I have added. Like so:
Now, whenever the user wants to search through the database, because I have null checks in my searches, whenever the program comes across that empty line between my original data and the new data that has been added, It will not continue the search, therefore any information that the user has added to the database is rendered useless and Java won't be able to search for it because of the empty line that separates it.
Basically, either I keep the pw.println() and have all my data come up but have a space inbetween the original data so It can't be searched for, OR i can remove it and then all new data that is added appears on the same line, which is not what I want.
This is the code for adding data to the txt file:
public static void add() throws IOException
{
String filename="Elements.txt";
PrintWriter pw = new PrintWriter(new FileWriter(filename,true));
pw.println();
String element=JOptionPane.showInputDialog(null, "Enter name of element.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(element + ",");
String symbol=JOptionPane.showInputDialog(null, "Enter symbol of element.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(symbol + ",");
String atomicNumber=JOptionPane.showInputDialog(null, "Enter atomic number.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(atomicNumber + ",");
String atomicMass=JOptionPane.showInputDialog(null, "Enter atomic mass", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(atomicMass + ",");
String valence=JOptionPane.showInputDialog(null, "Enter # of valence electrons.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(valence);
pw.close();
}
Is there any way I can manipulate the cursor on the txt file to ensure that all new data added shows up properly so the user can search for it afterwards? Opening up the txt file and placing the cursor where I want to didn't work.
The idea is to do println() (which adds a line end) at the end of writing whatever should be on a line. If you println() before any other data, it will very likely create an empty line (unless the last line is without a line end).
String filename="Elements.txt";
PrintWriter pw = new PrintWriter(new FileWriter(filename,true));
String element= ... ;
pw.write(element + ",");
// ... more ...
String valence=...;
pw.write(valence);
pw.println();
pw.close();
How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite
I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
public static void replaceSelected(File file, String type) throws IOException {
// we need to store all the lines
List<String> lines = new ArrayList<String>();
// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();
// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
I think most convenient way is:
Read text file line by line using BufferedReader
For each line find the int part using regular expression and replace
it with your new value.
Create a new file with the newly created text lines.
Delete source file and rename your new created file.
Please let me know if you need the Java program implemented above algorithm.
Hard to answer without the complete code...
Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.
You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.
Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.