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
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();
}
}
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]);
am new to java programming I need a program to read a certain information from a file and select the particular informationwhich is needed and then write this particular information into a text file .
{
BufferedReader in = new BufferedReader (newFileReader("C:/Users/ngorentl/"));
String info = "";
String info1 = "";
int startLine = 111 ;
int endLine = 203 ;
int sl = 221;
int el =325;
// reading only the specific info which is needed and that is printing in the console
for (int i = 0; i < startLine; i++) { info = in.readLine(); }
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
}
for (int j = 203; j < sl; j++) { info1 = in.readLine(); }
for (int j = sl; j < el + 1; j++) {
info1 = in.readLine();
System.out.println(info1);
}
// having a problem from here i dont know whether this is the correct approach
File fin = new File(info); // getting an error here
FileInputStream fis = new FileInputStream(fin);
BufferedReader is = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream("hh.txt");
OutputStreamWriter osw= new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
String aLine = null;
while ((aLine = is.readLine()) != null) {
bw.write(aLine);
bw.newLine();
bw.flush();
bw.close();
is.close();
}
in.close();
}
File fin = new File(String fileName) is the correct syntax.
eg.
File fin = new File("C:\abc.txt");
[UPDATE]
Assuming your question is about writing a String to file.
In Java 7
try( PrintWriter out = new PrintWriter( "filename.txt" ) ){
out.println( info);
}
In Java 6 or below, use
try {
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(info);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
and possible correction of your code, so variable info has all that information
for (int i = startLine; i < endLine + 1; i++) {
info += in.readLine();
}
System.out.println(info);
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);
}
}
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();
}
}