FileReader/Scanner reading file name rather than contents of .txt file - java

I'm trying to implement a Huffman algorithm that takes in characters from a .txt file. The txt file contains a paragraph of text. Right now when I run the program like so
java HuffmanCode large.txt
it produces output, but what it evaluated was the name of the file, "large.txt", rather than the text inside the file large.txt. How do I get it to read the contents instead?? Thanks for your help.
public static void main(String[] args) throws IOException {
String inputFileName = args[0];
FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);
int[] charFreqs = new int[256];
// read each character and record the frequencies
for (char c : inputFileName.toCharArray())
charFreqs[c]++;
// build tree
HuffmanTree tree = buildTree(charFreqs);
// print out results
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
printCodes(tree, new StringBuffer());
}
}

You were really close - you're just iterating over inputFileName.toCharArray(), which is giving you the characters in the file name. You need to read characters from your in variable (which will give you the file contents) instead, eg:
while (in.hasNextLine())
{
char[] line = in.nextLine().toCharArray();
for (char c : line)
charFreqs[c]++;
}
Note this will probably discard any newline characters in the file, so if you want to count them you'll probably have to do it manually. Or switch to reading raw char[]s from the FileReader you already have, which is probably a better approach than above (you want raw character data, not "text" data, which is what Scanner operates on).

Related

How to replace specific String in a text file by java?

I'm writing a program with a text file in java, what I need to do is to modify the specific string in the file.
For example, the file has a line(the file contains many lines)like "username,password,e,d,b,c,a"
And I want to modify it to "username,password,f,e,d,b,c"
I have searched much but found nothing. How to deal with that?
In general you can do it in 3 steps:
Read file and store it in String
Change the String as you need (your "username,password..." modification)
Write the String to a file
You can search for instruction of every step at Stackoverflow.
Here is a possible solution working directly on the Stream:
public static void main(String[] args) throws IOException {
String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";
try (Stream<String> stream = Files.lines(Paths.get(inputFile));
FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
try {
fop.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
You can try like this:
First, read the file line by line and check each line if the string you want to replace exists in that, replace it, and write the content in another file. Do it until you reach EOF.
import java.io.*;
public class Files {
void replace(String stringToReplace, String replaceWith) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("/home/asn/Desktop/All-copy.txt"));
String line;
while((line=in.readLine())!=null) {
if (line.contains(stringToReplace))
line = line.replace(stringToReplace, replaceWith);
out.write(line);
out.newLine();
}
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
Files f = new Files();
f.replace("amount", "####");
}
}
If you want to use the same file store the content in a buffer(String array or List) and then write the content of the buffer in the same file.
If your file look similar to this:
username:username123,
password:password123,
After load file to String you can do something like this:
int startPosition = file.indexOf("username") + 8; //+8 is length of username with colon
String username;
for(int i=startPosition; i<file.length(); i++) {
if(file.charAt(i) != ',') {
username += Character.toString(file.charAt(i));
} else {
break;
}
System.out.println(username); //should prong username
}
After edit all thing you want to edit, save edited string to file.
There are much ways to solve this issue. Read String docs to get to know operations on String. Without your code we cannot help you enough aptly.
The algorithm is as follows:
Open a temporary file to save edited copy.
Read input file line by line.
Check if the current line needs to be replaced
Various methods of String class may be used to do this:
equals: Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
equalsIgnoreCase: Compares this String to another String, ignoring case considerations.
contains: Returns true if and only if this string contains the specified sequence of char values.
matches (String regex): Tells whether or not this string matches the given regular expression.
startsWith: Tests if this string starts with the specified prefix (case sensitive).
endsWith: Tests if this string starts with the specified prefix (case sensitive).
There are other predicate functions: contentEquals, regionMatches
If the required condition is true, provide replacement for currentLine:
if (conditionMet) {
currentLine = "Your replacement";
}
Or use String methods replace/replaceFirst/replaceAll to replace the contents at once.
Write the current line to the output file.
Make sure the input and output files are closed when all lines are read from the input file.
Replace the input file with the output file (if needed, for example, if no change occurred, there's no need to replace).

How to take a specific line from a text file and read it into an array? (Java)

I've been trying to code a quiz game in javafx where I store the questions on a text file and then randomize a number then use it to call the line of the same number on the text file and read it into an array.
After looking online I can only seem to find how to read a text file line by line instead of a specific line. I also use the following code to read the text file but am unsure where to go on from there.
File file = new File("/Users/administrator/Desktop/Short Questions.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
This may help you
You need to change file path as per your file location
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\everestek22\\Desktop\\Invoice.txt"));
String[] strArray =
bufferedReader.lines().map(String::new).toArray(String[]::new);
// String line = bufferedReader.readLine();
// while (line != null) {
// System.out.println(line);
// line = bufferedReader.readLine();
// String[] strArray = bufferedReader.lines().map(String::new).toArray(String[]::new);
// }
bufferedReader.close();
for (String s : strArray) {
System.out.println(s);
}
}
}
Don't bother trying to read specific lines from the file, just read all the lines from the file, then lookup your question by index in the resultant list.
List<String> questions = Files.readAllLines(
Paths.get("<your file path>")
);
Then you could choose a question at random:
Random random = new Random(42);
int randomQuestionIndex = random.nextInt(questions.size());
String randomQuestion = questions.get(randomQuestionIndex);
Using 42 as the seed to the random number generator makes the random sequence repeatable, which is good for testing. To have it truly psuedo-random, then remove the seed (e.g. just new Random());
If the structure of the data you wish to read is complex, then use a helper library such as Jackson to store and retrieve the data as serialized JSON objects. If it is even more complex, then a database can be used.
If you have a really large file and you know the position in the file of each specific thing you wish to read, then you can use a random access file for lookup. For example, if the all the questions in the file are exactly the same length and you know how many questions are stored there, then a random access file might be used fairly easily. But, from your description of what you need to do, this is likely not the case, and the simpler solution of reading everything rather than using a random access file is better.

Code that can read in letters in a .txt file

I am writing a program thats supposed to read a simple text file and output a list of all the letters in that .txt file, ordered with the most frequently used letter to the least frequently used letter.
I have finished coding a working Java program that asks for file name and outputs the text within the file. But I am unsure how to go about outputting a list of the letters. What I am not sure specifically is what methods(if any) within the reader class I could use that reads in each letter in the .txt file. Any help would be appreciated!
This is current code:
// Here I import the Bufered Reader and file reader Libraries
// The Buffered Reader library is similar to Scanner Library and
// is used here to read from a text file. File reader will allow
// the program to access windows file system, get the text file
// and allow the Buufered Reader to read it in.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class TextFileReaderApp
{
// I added "throws exception" in case there is an an error in the
// main method, throw an exception, so it can prevent further
// errors from occuring if java doesnt know the main methods going
// to throw an error.
public static void main(String[] args) throws Exception
{
// below I diplay a welcome messgae to the user
System.out.println();
System.out.println("Welcome to the Text File Reader application!");
System.out.println();
// Below I create an instance of the Scanner class to get
// input from the user.
Scanner userInput = new Scanner(System.in);
String selection = "y"; //this is the string variable that's used in
//the while loop to continue the program.
// Below I created a while loop that continues the program if the user
// keeps selecting y as their selecion
while (selection.equalsIgnoreCase("y"))
{
// this line of code is supposed to ask the user for text file name under
// the C:/ directory and must not be hidden in any foler.
System.out.print("Please enter the name of the .txt file: C/");
FileReader file = new FileReader("C:/" + userInput.next());
// file object is used as a parameter in buffered reader.
BufferedReader textReader = new BufferedReader(file);
// below I create and initialize an object of type string called text that will
// store whats inside of the text file.
String text = "";
// I use the readLine statement to read line after line of the text.
// Once it has read everything it will return null.
String lineText = textReader.readLine();
// code below is a test for me to see if the code above works and is able to read
// the text inside the file and output it.
while(lineText != null)
{
// this reads the text line for line and ads it to the text variable for output.
text = text + lineText + "\n";
lineText = textReader.readLine();
}
System.out.println(text);
}
// These 3 code lines ask the user if he/she would like to continue with the program.
System.out.println();
System.out.print("Continue using the Text File Reader? (y/n): ");
choice = user_input.next();
System.out.println();
}
}
If you need to count letters / characters you can do it just as well on lines / words etc. No need to involve the Reader here.
for (char c : someString.toCharArray ()) {
// handle the character
}
Should work once you have any String from your file.
This reads all characters from textReader until EOF is reached or an exception occurs.
try {
for(int i = textReader.read(); i != -1 /* EOF */; i = textReader.read()) {
char c = (char) i;
// do whatever you want with your char here
}
} catch(IOException)
textReader.close();
first of all you might want to use a StringBuilder instead of your String text because of alot better performance.
"text = text + lineText" will create another String object every time it is executed, StringBuilder works better in this case).
One way to achieve what you want is to read character for character of your textLine and use a switchcase block with all letters and add them to an array containing integers when they occur. Example:
int[] array = new int[26];
switch(character){
case "a":
array[0] += 1;
break;
case "b":
array[1] += 1;
break;
//....
}
and so on...
in the end you use a simple for loop and print the values of your array. Now you see how many times you have entered which character.

how to read the \n in a txt file for using in split

I have this code here
java.io.File file=new java.io.File("deneme2.txt");
try{
Scanner input=new Scanner(file);
while(input.hasNext()){
String inputFile= input.nextLine();
String[] sequences =inputFile.split(" ");
It reads the file but I have to edit each file since I can not read .txt when the input is like this
ATGAGATACG
AGTCTCTAG
but I can read when I make
ATGAGATACG AGTCTCTAG
I tried to make \n and something like that but I couldn't.
So can you guys help me.
AND I know for sure that it has a very simple solution :) a solution that I'm not aware of tho
edit:in first example the 2 sequences are divided with a shift enter but the second one is divided with a single space
It sounds like you want to make the code that reads the file independent of the file format. To some extent, that's not possible. Any program has to assume some kind of pattern to the input -- be it XML, delimited text etc. So that breaks it up into two approaches: Either make the file fit the code or make the code fit the file.
From your description, I'm guessing you want to be able to read a sequence of characters that is delimited by whitespace -- any whitespace (' ', '\n', '\t'), yes? If that's true, don't limit yourself to reading by line. Just read each token. This, of course, assumes each token is what you want.
I created a test file with the content
abcd efg h
ijklm op
qrs
That has newlines, spaces and tabs. Then I fed it to the following code:
public static void main(String[] args){
try{
Scanner scanner = new Scanner(new File("testFile.txt"));
List<String> list = new ArrayList<String>();
while(scanner.hasNext()){
String s = scanner.next();
list.add(s);
}
scanner.close();
System.out.println(list);
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
Which gives the output
[abcd, efg, h, ijklm, op, qrs]
Is it possible you want to create an array of sequences? Like you want this file
ATGAGATACG <-- each of these being a sequence
AGTCTCTAG
to become an array like this
String[] sequences = {"ATGAGATACG", "AGTCTCTAG"};
If that's the case, you can just do something like this
List<String> sequences = new ArrayList<String>(); <-- create a list
java.io.File file=new java.io.File("deneme2.txt");
try{
Scanner input = new Scanner(file);
while(input.hasNextLine()){
sequences.add(input.nextLine().trim()); <-- add to the list each line
}
Edit
If its only two lines why not just do this, and forget the loop
String s1;
String s2;
try {
Scanner input = new Scanner(file);
s1 = input.nextLine().trim();
s2 = input.nextLine().trim();
} catch(.. ){
}
// do something with s1
// do something with s2

Finding and replacing words in a text file with Scanner and Printwriter classes

I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.

Categories

Resources