Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, I want to change a value in the file Utilizadores.txt
the default value is zero but when i click in the button the value has to change to 10 and every time i do a new one the value gets +10
the problem is when e try to do that the space where it should appear the (10/20/30...) appears blank
PS: it only changes in the lines of the file that have a certain ID(the id of my user)
private void ConfirmarActionPerformed(java.awt.event.ActionEvent evt) {
String filePath = "Reservas.txt";
File file = new File(filePath);
try {
FileWriter fw1 = new FileWriter(file, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(this.id+ "-" + cbxrestaurante.getSelectedItem().toString() + "-" + Dia.getText() + "-" + Hora.getText() + "-" + Lugares.getText());
bw1.newLine();
bw1.close();
fw1.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ClienteForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClienteForm.class.getName()).log(Level.SEVERE, null, ex);
}
String filePath1 = "Utilizadores.txt";
File file1 = new File(filePath1);
try {
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(file1, true);
PrintWriter bw = new PrintWriter(fw);
/*BufferedReader br = new BufferedReader(new FileReader(file1));
FileWriter fw = new FileWriter(file1, true);
PrintWriter bw = new PrintWriter((file1), "UTF-8");*/
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file1, true)));
Object[] lines = br.lines().toArray();
Integer[] getPontos = new Integer[lines.length];
String[] identificador = new String[lines.length];
String[] cartao = new String[lines.length];
String[] Pass = new String[lines.length];
String[] Nome = new String[lines.length];
String[] NIF = new String[lines.length];
String[] Tele = new String[lines.length];
String Zero = "zero";
String[] Morada = new String[lines.length];
String[] Localidade = new String[lines.length];
String[] dono = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
String[] row = lines[i].toString().split("-");
if (Objects.equals(Zero, row[10])||Integer.parseInt(row[10])==0) {
getPontos[i] = 0;
} else {
getPontos[i] = Integer.parseInt(row[10]);
}
identificador[i] = row[1];
cartao[i] = row[2];
Pass[i] = row[3];
Nome[i] = row[4];
NIF[i] = row[5];
Tele[i] = row[6];
Morada[i] = row[7];
Localidade[i] = row[8];
dono[i] = row[9];
if (Integer.parseInt(identificador[i]) == this.id) {
if (getPontos[i] == 0) {
getPontos[i] = 10;
} else {
getPontos[i] = getPontos[i] + 10;
}
}
}
fr.close();
br.close();
File temp = new File("Utilizadores.txt");
if (temp.exists()) {
RandomAccessFile raf = new RandomAccessFile(temp, "rw");
raf.setLength(0);
}
for (int i = 0; i < lines.length; i++) {
bw.write("UserId-");
bw.write(identificador[i] + "-");
bw.write(cartao[i] + "-");
bw.write(Pass[i] + "-");
bw.write(Nome[i] + "-");
bw.write(NIF[i] + "-");
bw.write(Tele[i] + "-");
bw.write(Morada[i] + "-");
bw.write(Localidade[i] + "-");
bw.write(dono[i] + "-");
bw.write(getPontos[i]);
bw.write("\r\n");
}
bw.close();
fw.close();
this.dispose();
} catch (FileNotFoundException ex) {
System.out.println("Import nao funciona");
} catch (IOException ex) {
Logger.getLogger(ClienteForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
Try to convert your Integer to String:
bw.write( String.valueOf(getPontos[i]));
instead
bw.write(getPontos[i]);
Related
I have a program that encode and decodes with my custom cipher, text files and lossless media files, but the problem is that over 2MB it crashes.
void doTheRabi(File f, byte[] hashedPass) {
try {
// BufferedReader br = new BufferedReader(new InputStreamReader(new
// FileInputStream(f))); // legge il file
// String response = new
// String(Files.readAllBytes(Paths.get(f.getAbsolutePath()))); // scrive tutto
// il file in memoria
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String response = new String(); // ASSEGNO IL CONTENUTO DEL FILE IN QUESTA STRINGA
for (String line; (line = br.readLine()) != null; response += line + "\n")
;
response = response.replace("\n", "newline").replace("\r", "newrow"); // rimpiazzo le new line con "newline"
// e "newrow"
byte[] encodedfile = response.getBytes(StandardCharsets.UTF_8); // trasformo il file in byte
byte[] result = new byte[encodedfile.length]; // variabile temporanea
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (encodedfile[i] + hashedPass[hpc++]); // algoritmo rabi
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String encodedresult = Base64.getEncoder().encodeToString(result); // restituisco il risultato in base64
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(encodedresult /* + "extension=" + extString */); // scrivo nel file tutto il risultato
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path + ".rab1";
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
// operazione inversa
void killTheRabi(File f, byte[] hashedPass) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String response = new String();
for (String line; (line = br.readLine()) != null; response += line)
;
byte[] decodedfile = Base64.getDecoder().decode(response);
byte[] result = new byte[decodedfile.length];
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (decodedfile[i] - hashedPass[hpc++]);
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String resultString = bytesToString(result);
String finalres = resultString.replace("newline", "\n").replace("newrow", "\r");
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(finalres);
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path.replace(".rab1", "");
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
What am I doing wrong? I think it's because the memory gets full, since java uses a virtual machine, but I don't know a way to enhance the memory usage, maybe using buffers but am I not using them already?
Since you are possibly holding quite a bit of data in memory, try the following:
Increase maximum heap size to be used by the JVM by starting with the parameter -Xmx2048m or more
I'm trying to modify text in a file but instead of modifying it, it is just adding a new line with the new information:
Here's my code
String id= IDSearch.getText();
String newname = NameText.getText();
String newbarcode = BarcodeText.getText();
String newsupplier= SupplierText.getText();
String newamount1= AmountText.getText();
ArrayList<Item> ItemsList = new ArrayList<>();
if (id.isEmpty() || newname.isEmpty() || newbarcode.isEmpty() || newsupplier.isEmpty() || newamount1.isEmpty()) {
JOptionPane.showMessageDialog(this, " Please Fill all fields");}
else{
try {
File Items = new File ("Items.txt");
FileReader fr = new FileReader(Items);
BufferedReader br = new BufferedReader(fr);
String data;
Item tempItem;
while ((data = br.readLine()) != null) {
tempItem = new Item(data);
if (tempItem.getID().equals(IDSearch))
{
tempItem.setItemName(newname);
tempItem.setItemBarcode(newbarcode);
tempItem.setSupplierID(newsupplier);
tempItem.setAmount(newamount1);
}
ItemsList.add(tempItem);
}
try (PrintWriter pw = new PrintWriter(new FileWriter(Items, true))) {
ItemsList.forEach((item) -> {
pw.println(newname + ";" + newbarcode+ ";" + newsupplier + ";" + newamount1);
});
JOptionPane.showMessageDialog(this, "Student Updated Succesfully");
}
}catch (IOException ex) {
}
}
}
I can't seem to be able to update the tex file the way it was supposed to update. Any help would be much appreciated!
You have append set to true. Doing new FileWriter(Items, false) or just (new FileWriter(Items) should fix the issue.
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 am Splitting large files along a Line END OF STATEMENT and writing new files. I need to name the files with a running number i.e Statement1, Statement2.... Here is what I have:
String[] filenames1 = statements.list(only);//only is filenamefilter
int count;
for (int k = 0; k < filenames1.length; k++) {
try {
FileInputStream fs = new FileInputStream("C:/statements/" + filenames1[k]);
System.out.println(filenames1[k]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
count = 0;
FileOutputStream fos = new FileOutputStream("C:/ABC Statements/Statement" + count + ".RPT");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
while ((lines = br.readLine()) != null) {
String mine = lines.trim();
if (mine.startsWith("********END OF STATEMENT********")) {
bw.close();
fos.close();
count++;
fos = new FileOutputStream("C:/ABC Statements/Statement" + count + ".RPT");
bw = new BufferedWriter(new OutputStreamWriter(fos));
continue;
}
if (mine.isEmpty()) {
continue;
}
bw.write(lines);
bw.newLine();
bw.flush();
}
fs.close();
br.close();
fos.close();
bw.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
I am getting only one file with Statement0 Meaning the names are getting overwritten. What Exactly am I doing wrong with count++
You should append an identifier to your output files, to know to what source file they are related, and prevent overwriting.
For instance :
String srcPrefix = filenames1[k].substring(0, filenames1[k].lastIndexOf('.'));
String destFilePath = "C:/ABC Statements/Statement" + "_" + srcPrefix + "_" + count + ".RPT";
I actually got it. Initializing count outside the for loop somehow solved it.
String[] filenames1 = statements.list(only);//only is filenamefilter
int count = 0;
for (int k = 0; k < filenames1.length; k++) {
try {
FileInputStream fs = new FileInputStream("C:/statements/" + filenames1[k]);
System.out.println(filenames1[k]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileOutputStream fos = new FileOutputStream("C:/ABC Statements/Statement" + count + ".RPT");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
while ((lines = br.readLine()) != null) {
String mine = lines.trim();
if (mine.startsWith("********END OF STATEMENT********")) {
bw.close();
fos.close();
count++;
fos = new FileOutputStream("C:/ABC Statements/Statement" + count + ".RPT");
bw = new BufferedWriter(new OutputStreamWriter(fos));
continue;
}
if (mine.isEmpty()) {
continue;
}
bw.write(lines);
bw.newLine();
bw.flush();
}
fs.close();
br.close();
fos.close();
bw.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
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());
}
}
});