Newbie here. My goal is to read a txt file, eliminate characters ("-" and " "), and replace the existing text with the new cleaned up text.
example: 855-555-1234 >> 8555551234.
I'm stuck on my append boolean. I'm using the guides here and here.
When my append is true then I get the text that I want at the end of the file, but when it is false, the file is completely blank.
My main method looks like:
public class Main {
public static void main(String[] args) throws IOException{
String file_name = "C:/TollFreeToPort.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
WriteFile data = new WriteFile(file_name, true);
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
data.writeToFile(aryLines[i]);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
My ReadFile Class:
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine()
.replace("-", "")
.replace(" ", "");
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
My WriteFile Class:
package textfiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile (String textLine) throws IOException{
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
Related
A have four classes: Main, Read, Author, Commands.
In Read class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class Read {
static ArrayList<String> arAuthor = new ArrayList<>();
static ArrayList<String> arCommand = new ArrayList<>();
public static ArrayList<String> getArAuthor() {
return arAuthor;
}
public static void setArAuthor(ArrayList<String> arAuthor) {
Read.arAuthor = arAuthor;
}
public static ArrayList<String> getArCommand() {
return arCommand;
}
public static void setArCommand(ArrayList<String> arCommand) {
Read.arCommand = arCommand;
}
public static void main(String[] args) {
BufferedReader author;
BufferedReader command;
String thisLine;
String thisLine1;
try {
author = new BufferedReader(new FileReader(args[0]));
command = new BufferedReader(new FileReader(args[1]));
while ((thisLine = author.readLine()) != null) {
System.out.println(thisLine);
arAuthor.add(thisLine);
}
while ((thisLine1 = command.readLine()) != null) {
System.out.println(thisLine1);
arCommand.add(thisLine1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My code works as Read.java args[0] args[1] but i want it to work like Main.java args[0] args[1]. I am new to Java so ı can't figure how can i pass this arguments to Main.java
Solution:
public class Reader {
public List<String> arAuthor = new ArrayList<>();
public List<String> arCommand = new ArrayList<>();
public void read(String first, String second) throws IOException {
String thisLine;
String thisLine1;
try (BufferedReader author = new BufferedReader(new FileReader(first));
BufferedReader command = new BufferedReader(new FileReader(second));){
while ((thisLine = author.readLine()) != null) {
System.out.println(thisLine);
arAuthor.add(thisLine);
}
while ((thisLine1 = command.readLine()) != null) {
System.out.println(thisLine1);
arCommand.add(thisLine1);
}
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
reader.read(args[0], args[1]);
System.out.println(reader.arAuthor);
System.out.println(reader.arCommand);
}
}
I'm trying to print a .txt on the screen.I have a menu with different options and I don't know why it fails. The file directory should be defined by the string FITXER. I only want to print the text file, I don't need to save the content. The bug is on the BufferedReader and FileReader arxiu, it's the name of the file variable that gets the value of FITXER.
import java.util.Scanner;
import java.io.*;
public class Copiador {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
Copiador programa = new Copiador();
programa.inici();
}
public void inici() throws IOException {
int opcio;
do {
System.out.println("Llegir (1)");
System.out.println("Copiar (2)");
System.out.println("Surtir (3)");
opcio = sc.nextInt();
switch (opcio) {
case 1:
Llegir();
break;
case 2:
System.out.println("Skipped Consultar");
//Consultar(nomusuaris);
break;
}
} while (opcio != 3);
sc.close();
}
public void Llegir() throws IOException {
String FITXER;
File arxiu = null;
FileReader fr = null;
BufferedReader br = null;
System.out.println("Que vols llegir?");
FITXER = sc.nextLine();
arxiu = new File(FITXER);
fr = new FileReader(arxiu);
br = new BufferedReader(fr);
String linea;
while ((linea = br.readLine()) != null)
System.out.println(linea);
System.out.println("Confirmat");
fr.close();
}
}
I am attempting to add this large txt file into an array list then sort the data. Then put 15000 lines in various temp files. I am unable to put the data into each file. Here is my code:
package bigfilesorter2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class bigfilesorter2 {
public static final int NUM_LINES = 15000;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("Aesop_Shakespeare_Shelley_Twain.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<String> arraylist = readingfile(br);
//System.out.println(arraylist);
makingfiles(br, arraylist);
}
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
start = end + 1;
end += 15000;
}
}
public static ArrayList<String> readingfile(BufferedReader br) throws FileNotFoundException, IOException {
//Read in file
Scanner s = new Scanner(new File("Aesop_Shakespeare_Shelley_Twain.txt"));
int count = 0;
ArrayList<String> arraylist = new ArrayList<String>();
while (s.hasNext()) {
count++;
arraylist.add(s.nextLine());
}
//} catch (IOException e) {e.printStackTrace();}
Collections.sort(arraylist);
//System.out.println(arraylist);
return arraylist;
}
}
Any help would be appreciated. the commas were just the file being sorted..................
"it looks like your post is mostly code"
You need to create a list of sublists where each sublist holds 15000 lines. Given below is the complete code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class BigFileSorter {
public static final int NUM_LINES = 15000;
public static final int NUM_FILES = 20;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<ArrayList<String>> list = readingfile(br);
makingfiles(br, list);
}
public static void makingfiles(BufferedReader br, ArrayList<ArrayList<String>> list) throws IOException {
if (list != null) {
for (int i = 0; i < NUM_FILES; i++) {
File file = new File("Filee" + i + ".txt");
FileWriter fw = new FileWriter(file);
ArrayList<String> subList = list.get(i);
for (String str : subList) {
fw.write(str + System.lineSeparator());
}
fw.close();
}
}
}
public static ArrayList<ArrayList<String>> readingfile(BufferedReader br)
throws FileNotFoundException, IOException {
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
ArrayList<String> subList;
String line;
try {
for (int i = 0; i < NUM_FILES; i++) {
subList = new ArrayList<String>();
for (int j = 0; j < NUM_LINES; j++) {
line = br.readLine();
if (line == null) {
break;
}
subList.add(line);
}
Collections.sort(subList);
list.add(subList);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
return list;
}
}
Feel free to comment in case of any doubt.
Maybe something like this as an inner for loop in your makefiles method.
// outside of the for loops
int start = 0;
int end = 15000;
// inner for loop
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
// end of outer for loop
start = end + 1;
end += 15000;
So complete method:
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
bw.flush();
bw.close();
fw.close()
start = end + 1;
end += 15000;
}
}
Should work for what you asked in the comment, but you still have to change your read method so that it reads all the lines in one arraylist
I have been asked to write a program that will read a file as it is updated (4 times/millisecond) and print the number of lines to the system. To do this, I have the following code:
package threadFile;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile
{
private String path;
public ReadFile(String file_name)
{
path = file_name;
}
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[]textData = new String[numberOfLines];
int i;
for(i=0; i< numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
#SuppressWarnings("unused")
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
The above code is meant to open a text file and read the number of lines there are. My issue is, getting the program to update as the file is written to (by another section of the program).The below code is a thread, and is meant to call into ReadFile for instructions.
I need the program to constantly read the contents, and accurately update the line count as it is edited.
If I understand correctly your requirement you want to use one file for Inter Process Communication (or inter thread-communication to be more exact for your case). If this is the case you probably want to use the file as MemoryMapped file.
A simple description of MemoryMapped file usage is done here.
As it was already said, Java 1.7 Watch Service is also a solution that could work.
Solution
The solution to my problem was a little more involved than expected.
Reading Files
package threadFile;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PrintReader implements Runnable
{
#SuppressWarnings("unused")
private final String taskName;
final String file_name = "C:/Users/wigginsm/Desktop/Log.txt";
public PrintReader(String name)
{
taskName = name;
}
public void run()
{
boolean loop = true;
while(loop = true)
try
{
FileReader fr = new FileReader(file_name);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
int count = 0;
while(line!=null)
{
count++;
line=br.readLine();
}
FileInputStream fileIn = new FileInputStream(file_name);
BufferedReader fileR = new BufferedReader(new InputStreamReader(fileIn));
String strLine = null, tmp;
while((tmp = fileR.readLine())!=null)
{
strLine = tmp;
}
String lastLine = strLine;
System.out.println("Last entered line: " + lastLine + "\n" + "Total number of Lines: " + count);
br.close();
fileR.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
The above class is responsible for reading the file, declared with "file_name".
Writing to Files
package threadFile;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
public class WriteToFile implements Runnable
{
#SuppressWarnings("unused")
private final String taskName;
class WriteFile
{
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path, boolean append_value)
{
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String timestamp) throws IOException
{
int i = 0;
while(i<1)
{
FileWriter write = new FileWriter(path, append_to_file);
Calendar current = Calendar.getInstance();
int ms = current.get(Calendar.MILLISECOND);
int minute = current.get(Calendar.MINUTE);
int second = current.get(Calendar.SECOND);
int hour = current.get(Calendar.HOUR_OF_DAY);
int day = current.get(Calendar.DAY_OF_YEAR);
int month = current.get(Calendar.MONTH)+1;
int year = current.get(Calendar.YEAR);
timestamp = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + ms;
PrintWriter print_line = new PrintWriter(write);
try
{
Thread.sleep(250);
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
print_line.printf("%s" + "%n", timestamp);
print_line.close();
}
}
}
//constructor
public WriteToFile(String name)
{
taskName = name;
}
#SuppressWarnings("unused")
public synchronized void run()
{
boolean loop = true;
while(loop = true)
{
try
{
String file_name = "C:/Users/wigginsm/Desktop/Log.txt";
Calendar current = Calendar.getInstance();
int ms = current.get(Calendar.MILLISECOND);
int minute = current.get(Calendar.MINUTE);
int second = current.get(Calendar.SECOND);
int hour = current.get(Calendar.HOUR_OF_DAY);
int day = current.get(Calendar.DAY_OF_YEAR);
int month = current.get(Calendar.MONTH)+1;
int year = current.get(Calendar.YEAR);
String timestamp = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + ms;
WriteFile data = new WriteFile(file_name, true);
data.writeToFile(timestamp);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
}
The above code is responsible for writing to the file. The only reason for the while loop to continue indefinitely is due to my program specification. This can easily be altered to fit any iteration.
Execution
package threadFile;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class execute
{
public static void main(String[] args)
{
final String file_name = "C:/Users/wigginsm/Desktop/Log.txt";
WriteToFile writes = new WriteToFile(file_name);
PrintReader reads = new PrintReader(file_name);
ExecutorService thread = Executors.newCachedThreadPool();
thread.execute(reads);
thread.execute(writes);
thread.shutdown();
}
}
This is the main class, it is responsible for handling the threading. Both PrintWrite and WriteToFile have the "synchronize" statement, as run() in both classes accesses the file.
this code couldn't find the files that the buffered reader is supposed to read from it and i have the files in the src folder in eclipse project and it still doesn't read from file so does anybody have any idea about what the problem is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.*;
import java.util.ArrayList;
public class Encrypt {
public static ArrayList<String> data = new ArrayList<String>();
public static BigInteger [] keys = new BigInteger[3];
public static BigInteger n;
public static double e;
public static BigInteger d;
public static String line;
public static String result;
public static String [] temp;
public static BigInteger tempVar;
public static BigInteger tempResult;
public static int tempVar2;
public static void encryption(ArrayList<String> data) throws IOException{
for (int i = 0; i<data.size(); i++){
if(data.get(i)!= null){
temp = new String[data.get(i).split(" ").length];
temp = data.get(i).split(" ");
for(int j = 0; j<temp.length;j++){
for (int k = 0; k< temp[j].length(); k++){
tempVar2 = (int)temp[j].charAt(k);
tempVar=BigInteger.valueOf((long)Math.pow(tempVar2,e));
tempResult = (tempVar.remainder(n));
result =""+ tempResult;
LogEncrypt(result);
}
}
}
}
}
public static void read() throws IOException{
try {
BufferedReader br = new BufferedReader(new FileReader("plainText.txt"));
System.out.println(br.ready());
while ((line = br.readLine()) != null) {
data.add(br.readLine());
}
System.out.println("done with text");
} catch (FileNotFoundException e) {
System.out.println("please add the text file");
e.printStackTrace();
}
try {
BufferedReader ba = new BufferedReader(new FileReader("Key.txt"));
System.out.println(ba.ready());
int i =0;
while ((line = ba.readLine()) != null) {
keys[i] = new BigInteger(ba.readLine());
i++;
}
n = keys[0];
e = keys[1].doubleValue();
d = keys[2];
System.out.println("done with key");
} catch (FileNotFoundException e) {
System.out.println("please add the key file");
e.printStackTrace();
}
}
public static void LogEncrypt(String result) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
try {
out.write(result);
out.newLine();
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
}
}
public static void main(String[]args) throws IOException{
read();
encryption(data);
}
}
Put the file outside of the src, or at least add "src/" to the file location