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);
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 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 text file, I want to read it and place it into my hash table.
Then print it.
I have written a block of code, what am I doing wrong?
public static void main(String[] args) throws FileNotFoundException, IOException {
Hashtable< Integer, String > hash = new Hashtable< Integer, String >();
BufferedReader rd = new BufferedReader( new FileReader ("students.txt"));
String line = "";
int i = 0;
while (line != null){
line = rd.readLine();
hash.put(i, line);
i++;
}
for ( int j = 0 ; j < hash.size() ; j++){
System.out.println(hash.get(j));
}
}
Code looks good . Correcting one bug below
BufferedReader br = new BufferedReader(new FileReader ("students.txt"));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
I am using your code and I have corrected some bugs...
I think, this code is not right but he works :)
try{
Hashtable< Integer, String > hash = new Hashtable< Integer, String >();
BufferedReader rd = new BufferedReader( new FileReader ("students.txt"));
String line;
int i = 0;
while ((line = rd.readLine()) != null){
hash.put(i, line);
i++;
}
for ( int j = 0 ; j < hash.size() ; j++){
System.out.println(hash.get(j));
}
}catch(FileNotFoundException e){}catch (IOException e) {}
I have a file "a.txt" which contains the following lines:
14,15,16,17
13,16,15,14
15,17,12,13
...
...
I know that each line will always have 4 columns.
I have to read this file and split the lines based on delimiter (here it is ",") and write the value of each column in its corresponding file i.e. if value in a column is 14 then it has to be dumped/wriiten in 14.txt, if its 15 then it will be written in 15.txt and so on.
Here is what I have done till now:
Map <Integer, String> filesMap = new HashMap<Integer, String>();
for(int i=0; i < 4; i++)
{
filesMap.put(i, i+".txt");
}
File f = new File ("a.txt");
BufferedReader reader = new BufferedReader (new FileReader(f));
String line = null;
String [] cols = {};
while((line=reader.readLine()) != null)
{
cols = line.split(",");
for(int i=0;i<4;i++)
{
File f1 = new File (filesMap.get(cols[i]));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f1)));
pw.println(cols[i]);
pw.close();
}
}
So for line number 1 of file "a.txt", I will have to open, write and close files 14.txt,15.txt,16.txt and 17.txt
Again for line number 2, I have to again open,write and close files 14.txt,15.txt,16.txt and a new file 13.txt
So is there any better option in which I don't have to open and close the file which has already been opened earlier.
At the end of the complete operation I will close all the opened files.
Something like this should work:
Map <Integer, PrintWriter> filesMap = new HashMap<>();
...
if(!filesMap.containsKey(cols[i]))
{
//add a new PrintWriter
} else
{
//use the existing one
}
try
Set<String> s = new HashSet<>();
Scanner sc = new Scanner(new File ("a.txt")).useDelimiter("[\n\r,]+");
while(sc.hasNext()) {
String n = sc.next();
if (s.add(n)) {
FileWriter w = new FileWriter(n + ".txt");
w.write(n);
w.close();
}
}
sc.close();
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("a.txt");
BufferedReader reader = new BufferedReader(fr);
String line = "";
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
for (int i = 0; i < 4; i++) {
FileWriter fstream = new FileWriter(cols[i] + ".txt" , true);// true is for appending the data in the file.
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(cols[i] + "\n");
fbw.close();
}
}
}
Try this . I think you want to do like this way.
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();
}
}