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");
}
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 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 an ArrayList list of some lines from text file. I am trying to find these lines in a text file, if I find it I want to write it to another text file and delete it from the original file.
I wrote a code for that, it is working but not for the whole list, sometimes take one line and sometimes take more. and give me this message:
1 R101 100850 0
Exception caught : java.io.IOException: Stream closed
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fr1 = new FileWriter(outputFile);
BufferedWriter writer = new BufferedWriter(fr1);
String line;
int count = 1;
int z = 1;
while ((line = br.readLine()) != null) {
// System.out.println(z++ + ": ");
String subLine = line.substring(5, line.length() - 2);
// System.out.println(subLine);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
fr1.write(line);
fr1.write("\n");
fr1.flush();
fr.close();
removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
br.close();
fr1.close();
writer.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Can someone help me please?
String subLine = line.substring(5, line.length() - 2);
You are hard coding to take substring from index 5.
What happens when the length of line is less than 5? have a check if the line's length is less than 5 and only then proceed.
Also why are catching with 'Exception' ? try catching with a lower level exception like ArrayIndexOutOfBoundsException etc.
Thank you all for your help.
I figure out the problem, it was because I delete the file and create it again from temp file. in that case I lose the pointer to the file.
This is the code after I fix it if someone interested.
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
String subLine = line.substring(5, line.length() - 2);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
bufferedReader.close();
fileReader.close();
bufferedWriter.write(line+"\n");
bufferedWriter.flush();
bufferedReader = removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
bufferedWriter.close();
fileWriter.close();
bufferedReader.close();
fileReader.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static BufferedReader removeLineFromFile(String file, String lineToRemove) {
BufferedReader bufferedReader = null;
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
bw.write(line+"\n");
bw.flush();
}
}
bw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return null;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
FileReader fileReader = new FileReader(inFile);
bufferedReader = new BufferedReader(fileReader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return bufferedReader;
}
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());
}
}
});
I'm trying to read a text files and insert the data from these text files into a URL;
but i have this error "java.lang.illegalargumentexception contains a path separator file"
this is the read method that im using
>
public String ReadFile (String Path){
String res = null;
try {
String filePath = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + Path;
File file = new File(filePath);
if(file.exists()){
InputStream in = openFileInput(filePath);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
res = "";
String line;
while (( line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}else{
}
}else{
Toast.makeText(getApplicationContext(), "The File" + Path + " not Found" ,Toast.LENGTH_SHORT).show();
}
} catch(Exception e){
Toast.makeText(getApplicationContext(),e.toString() + e.getMessage(),Toast.LENGTH_SHORT).show();
}
return res;
}
> String sendername = ReadFile ("SenderName.txt");
String AccountName = ReadFile ("AccountName.txt");
String AccountPassword = ReadFile ("AccountPassword.txt");
String MsgText = ReadFile ("MsgText.txt");
Thanks,
- Though this error doesn't points there, but still have you given the permission to read External Storage in the Manifest.xml file
Try something like this..
public void readFile(String path){
File f = new File(path);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String read = new String();
String temRead = new String();
while((temRead = br.readLine())!=null){
read = read + temRead;
}
}