This is a program that allows the user to search for an item and then the program splits the items and stores them in 4 different textfields. However, below is a method for updating the retrieved items back to the file. The problem is whenever the user clicks on the update button, the line does update successfully, but the other lines in the file are deleted!
I am using an arraylist to store the searched item and also temporary file to write the item and then renaming it.
file.txt
ramal hotel1 10 uk
bren hotel2 20 france
gil hotel3 30 china
//Update to file
button9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try {
String stringSearch = textfield1.getText();
File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
File file = new File("file.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while (( line = bf.readLine()) != null){
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String a = textfield1.getText();
String b = textfield2.getText();
String c = textfield3.getText();
String d = textfield4.getText();
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
String thirdword = word[2];
String fourthword = word[3];
writer.write(line.replace("\t", "\t").replace(firstword, b).replace(secondword, c).replace(thirdword, d));
writer.flush();
}
writer.newLine();
}
writer.close();
bf.close();
filetemp.renameTo(file);
filetemp.deleteOnExit();
FileChannel src = new FileInputStream(filetemp).getChannel();
FileChannel dest = new FileOutputStream(file).getChannel();
dest.transferFrom(src, 0, src.size());
}catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
});
You're saving only that data back to the file which contains the string you're searching for and you're ignoring the other lines.
Add this to your code just after the if block
else{
writer.write(line);
writer.flush();
}
just before the following line:
writer.newLine();
So your code will look like this:
//Update to file
button9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try {
String stringSearch = textfield1.getText();
File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
File file = new File("file.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while (( line = bf.readLine()) != null){
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String a = textfield1.getText();
String b = textfield2.getText();
String c = textfield3.getText();
String d = textfield4.getText();
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
String thirdword = word[2];
String fourthword = word[3];
writer.write(line.replace("\t", "\t").replace(firstword, b).replace(secondword, c).replace(thirdword, d));
writer.flush();
}
else{
writer.write(line);
writer.flush();
}
writer.newLine();
}
writer.close();
bf.close();
filetemp.renameTo(file);
filetemp.deleteOnExit();
FileChannel src = new FileInputStream(filetemp).getChannel();
FileChannel dest = new FileOutputStream(file).getChannel();
dest.transferFrom(src, 0, src.size());
}catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
});
Related
I am able to read in a file right now, but I am confused on how to read then the strings line by line to run through a parser I created. Any suggestions would be helpful.
public void ReadBtn() {
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
String s = "";
int READ_BLOCK_SIZE = 100;
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
BufferedReader BR = new BufferedReader(InputRead);
while((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
getContactInfo(s);
}
InputRead.close();
} catch(Exception e) {
e.printStackTrace();
}
}
-Try this code. Replace sdCard path to your file path where mytextfile.txt exists.
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "mytextfile.txt";
String path = sdCard + "/" + MarketPath + "/";
File directory = new File(path);
if (directory.exists()) {
File file = new File(path + fileName);
if (file.exists()) {
String myData = ""; // this variable will store your file text
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can read all lines in an ArrayList:
public void ReadBtn() {
int READ_BLOCK_SIZE = 100;
ArrayList<String> linesList = new ArrayList<>();
// reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
BufferedReader br = new BufferedReader(InputRead);
String line = br.readLine();
while (line != null) {
linesList.add(line);
line = br.readLine();
}
InputRead.close();
// here linesList contains an array of strings
for (String s: linesList) {
// do something for each line
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am trying to replace multiple strings in a file from source as ArrayList. But the application is erasing the old string before replacing a new one. Please help.
public static void writeNewFile(File template, ArrayList<String> data) {
File file = template;
String nameToReplace = "((name))";
String productToReplace = "((product))";
String giftToReplace = "((gift))";
String giftValueToReplace = "((gift-value))";
String outputFileName = data.get(0);
String workingDirectory = System.getProperty("user.dir");
Scanner scanner = null;
try {
scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(workingDirectory + "\\Output\\" + outputFileName);
while (scanner.hasNextLine()) {
String line1 = scanner.nextLine();
writer.println(line1.replace(nameToReplace, data.get(1)));
writer.println(line1.replace(productToReplace, data.get(2)));
}
} catch (Exception e) {
System.out.println("Destination folder not found");
}
}
This worked for me
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String result = oldtext.replace(nameToReplace, data.get(1))
.replace(productToReplace, data.get(2))
.replace(giftToReplace, data.get(3));
// Write updated record to a file
FileWriter writer = new FileWriter(workingDirectory + "\\Output\\" + outputFileName);
writer.write(result);
writer.close();
} catch (IOException ioe) {
System.out.println("Write error");
}
I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.
I have a .txt file with the following content:
1 1111 47
2 2222 92
3 3333 81
I would like to read line-by-line and store each word into different variables.
For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.
My initial approach is as follows:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Kindly give me your suggestions. Thank You
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
try {
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Hope this Helps!
Check out BufferedReader for reading lines. You'll have to explode the line afterwards using something like StringTokenizer or String's split.
import java.io.*;
import java.util.Scanner;
class Example {
public static void main(String[] args) throws Exception {
File f = new File("main.txt");
StringBuffer txt = new StringBuffer();
FileOutputStream fos = new FileOutputStream(f);
for (int i = 0; i < args.length; i++) {
txt.append(args[i] + " ");
}
fos.write(txt.toString().getBytes());
fos.close();
FileInputStream fis = new FileInputStream("main.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
StringBuffer txt1 = new StringBuffer();
StringBuffer txt2 = new StringBuffer();
File f1 = new File("even.txt");
FileOutputStream fos1 = new FileOutputStream(f1);
File f2 = new File("odd.txt");
FileOutputStream fos2 = new FileOutputStream(f2);
while ((data = br.readLine()) != null) {
result = result.concat(data);
String[] words = data.split(" ");
for (int j = 0; j < words.length; j++) {
if (j % 2 == 0) {
System.out.println(words[j]);
txt1.append(words[j] + " ");
} else {
System.out.println(words[j]);
txt2.append(words[j] + " ");
}
}
}
fos1.write(txt1.toString().getBytes());
fos1.close();
fos2.write(txt2.toString().getBytes());
fos2.close();
br.close();
}
}
Hello I want to display my txt file but probably something is wrong! Any help? Here is my code:
public class Display extends Items{
public int countLines(String filename){
int lines = 0; //mporei na metrhsei mexri "int" grammes (~2.1 dis grammes)
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(filename);
// 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) {
lines++;//metrhths grammwn/eggrafwn
}
//close input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return lines;}
public String[] showAllRegisteredLessons(String filename, int size) {
String[] temp = new String[size+1]; //mexri "size" kataxwrhseis ma8hmatwn dld (mege8os "int")
try {
int x = 0;
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(filename);
// 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) {
//System.out.println(strLine.replace("#", " "));
temp[x] = strLine;
x++;
}
//close input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return temp;
}
public JPanel pinakas(String[] pinaka) {
int sr = 0;
//int ari8mos =0;
String[] COLUMN_NAMES = {"Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};
//pio panw mporoume na pros8esoume ws prwto column to "#", wste na deixnei ton ari8mo ths ka8e kataxwrhshs
DefaultTableModel modelM = new DefaultTableModel(COLUMN_NAMES, 0);
JTable tableM = new JTable(modelM);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(tableM), BorderLayout.CENTER);
Display disp = new Display();
while (pinaka[sr] != null) // !!!!tha ektupwsei kai mia parapanw "/n" logo ths kataxwrhshs prwtou h teleytaiou mahmatos
{
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5],temp5[6]};//edw mporoume sthn arxh na valoume to ari8mos gia na fainetai o ari8mos twn kataxwrhsewn
modelM.addRow(doge);
sr++;
//ari8mos++;
}
return mainPanel;
}
and in main()
if(category31=="ΣΚΥΛΟΙ"){
Display disp= new Display();
int numberofline=disp.countLines("Dogss.txt");
String[] tempΜ1 = disp.showAllRegisteredLessons("Dogss.txt",numberofline);
//System.out.println(numberofline);
JOptionPane.showMessageDialog(null, disp.pinakas(tempΜ1), "Καταχωρημένα Kατοικίδια", JOptionPane.PLAIN_MESSAGE);
break;
}
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at program.Display.pinakas(Display.java:83)
at program.Main.main(Main.java:334)
I bet the problem is in the following lines (which is probably line 83..):
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5],temp5[6]};
The array has only 6 elements. But you are accessing the 7th element with:
temp5[6]
That's why you get the ArrayIndexOutOfBoundsException.