Cannot find symbol IOUtils - java

Basically I am trying to take information from a text file and turn it into a string. The code I have is:
FileInputStream inputStream = new FileInputStream("filename.txt");
try
{
String everything = IOUtils.toString(inputStream);
}
finally
{
inputStream.close();
}
the error message I get is -->
java:53: cannot find symbol
symbol : class IOUtils
location: class CheckSystem
I assumed this was because of my imports, but I have io and util and even text imported (just as below)
import java.util.*;
import java.text.*;
import java.io.*;
Why can't I access the IOUtils class and its methods? If that cannot be answered, an alternative but very simple means of reading a text file into a string would be fine.

You don't need anything outside of standard JDK to read from a text file easily and efficiently. For example you can do so like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch(IOException e) {
}
finally {
br.close();
}
taken from: Reading a plain text file in Java
The everything String contains the contents of the file.txt, which must be located in the same directory as where the java class file is being run from.

Related

read any file efficiently in java as string

i'm working on a simple implementation of Huffman coding and it works fine for any files using some form of text encoding but when i try to read in any other format (e.g. .mp4 .png .exe) it still works but becomes extremely slow
(minutes instead of less than a second for the same size of file).
my question is is there another method i should be using to read these files so that the read speed depends on the size of the file not its format and if so what is it? thanks.
this is my IO class it uses a fileReader wrapped in a bufferedReader to read files based on a path entered in the console.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class IO {
public String readFile(String path, boolean includeNewLine) {
String returnString = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
int nLines = 0;
while((line = bufferedReader.readLine()) != null) {
if(nLines > 0 && includeNewLine) {
returnString += "\n";
}
returnString += line;
nLines++;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file '" + path + "'");
} catch(IOException e) {
System.out.println("Error reading file '" + path + "'");
}
return returnString;
}
}
Maybe this will help: FileInputStream vs FileReader
And, of course, change your method to use StringBuilder (but that's another issue).
With returnString you are creating new instance of String by appending the new line to previous line. Instead i would suggest you use StringBuilder as follows:
StringBuilder fileContent = new StringBuilder();
//do your stuff
fileContent.append(line);
In this way, you keep on reusing the same builder object. Also if you are reading binary content then better use class from InputStream hierarchy.
We do have Files class from nio package which you could use to get lines as below instead:
try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)) {
stream.forEach(s -> fileContent.append(s).append("\n"));
}
Another way, would be to use already tested code provided by Apache commons IO api FileUtils.readFileToString
As long as you are trying to interpret the file as a String you'll be running into problems with efficiency. Any binary format may produce a huge string, even exceeding the 64K maximum a string can hold as there may never be a byte you'll interpret as a end of line character ('\n').
You should interpret your file as a sequence of bytes. Use a memory mapped ByteBuffer for maximum efficiency.

Reading a line from a text file

I am trying to read a line from a text file, but the program keeps returning an error stating that the file's name cannot be located. Any ideas on how to solve the problem.
Source code:
import java.io.FileReader;
import java.io.BufferedReader;
public class Cipher {
public String file_name;
public Cipher(){
file_name = "/Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt";
}
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
Cipher cipher_1 = new Cipher();
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}
}
}
Upon debugging this is what I get,
Error:(25, 14) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Error:(30, 43) java: unreported exception java.io.IOException; must be caught or declared to be thrown
The above two lines are where :
Variable fr is initialized.
The while loop.
You are getting these errors because the methods and constructors you are calling throw exceptions. These either need to be caught with a try/catch block or be declared in the method signature.
These errors are compile time errors, not runtime. It's not saying that the file doesn't exist, but that you need to catch an exception just in case that is true.
Oracle Tutorial
Please Enter the complete path that is the Drive along with the folder location.
C:\....\Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt
Like this. It should be like when you copy paste in the explorer you can jump to the file directly.
If using MAC then, right click on the text file and properties and copy the location and paste it in your code.
In your code, below lines need to catch
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
Use try-catch block or throws Exception to handle it.
Your file path should include the entire path for example:
"C:\\Users\\John Doe\\Desktop\\Impactor_0.9.41.txt"
Notice I used an extra '\' but I'm not sure if that matters, however I always do that.
Also for clarity you could also change your br and fr like this, however what you did is fine as well. But it is important to do the opening of files in a try-catch block like this:
try{
br = new BufferedReader(new FileReader(cipher1.file_name));
} catch(FileNotFoundException e){
e.printStackTrace();
}
Also when reading and printing out file to console, put it in try catch:
try{
String current_line;
while((current_line = br.readLine()) != null){
System.out.println(current_line);
current_line = br.readLine();
}
} catch(IOException e){
e.printStackTrace();
}
try{
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}catch(Exception e)
e.printStackTrace();
{
You need to handle the exceptions generated by your reader

How to replace a line with a new line using Java

Using a Buffer reader I parse throughout a file. If Oranges: pattern is found, I want to replace it with ApplesAndOranges.
try (BufferedReader br = new BufferedReader(new FileReader(resourcesFilePath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("Oranges:")){
int startIndex = line.indexOf(":");
line = line.substring(startIndex + 2);
String updatedLine = "ApplesAndOranges";
updateLine(line, updatedLine);
I call a method updateLine and I pass my original line as well as the updated line value.
private static void updateLine(String toUpdate, String updated) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(resourcesFilePath));
PrintWriter writer = new PrintWriter(new File(resourcesFilePath+".out"), "UTF-8");
String line;
while ((line = file.readLine()) != null)
{
line = line.replace(toUpdate, updated);
writer.println(line);
}
file.close();
if (writer.checkError())
throw new IOException("Can't Write To File"+ resourcesFilePath);
writer.close();
}
To get the file to update I have to save it with a different name (resourcesFilePath+".out"). If I use the original file name the saved version become blank.
So here is my question, how can I replace a line with any value in the original file without losing any data.
For this you need to use the regular expressions (RegExp) like this:
str = str.replaceAll("^Orange:(.*)", "OrangeAndApples:$1");
It's an example and maybe it's not excactly what you want, but here, in the first parameter, the expression in parentesis is called a capturing group. The expression found will be replaced by the second parameter and the $1 will be replaced by the value of the capturing group. In our example Orange:Hello at the beggining of a line will be replaced by OrangeAndApples:Hello.
In your code, it seams you create one file per line ... maybe inlining the sub-method would be better.
try (
BufferedReader br = new BufferedReader(new FileReader(resourcesFilePath));
BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset);
) {
String line;
while ((line = br.readLine()) != null) {
String repl = line.replaceAll("Orange:(.*)","OrangeAndApples:$1");
writer.writeln(repl);
}
}
The easiest way to write over everything in your original final would be to read in everything - changing whatever you want to change and closing the stream. Afterwards open up the file again, then overwrite the file and all its lines with the data you want.
You can use RandomAccessFile to write to the file, and nio.Files to read the bytes from it. In this case, I put it as a string.
You can also read the file with RandomAccessFile, but it is easier to do it this way, in my opinion.
import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
public void replace(File file){
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Path p = Paths.get(file.toURI());
String line = new String(Files.readAllBytes(p));
if(line.startsWith("Oranges:")){
line.replaceAll("Oranges:", "ApplesandOranges:");
raf.writeUTF(line);
}
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Java: Having trouble reading from a file

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TextFile {
private static void doReadWriteTextFile() {
try {
// input/output file names
String inputFileName = "README_InputFile.rtf";
// Create FileReader Object
FileReader inputFileReader = new FileReader(inputFileName);
// Create Buffered/PrintWriter Objects
BufferedReader inputStream = new BufferedReader(inputFileReader);
while ((inLine = inputStream.readLine()) != null) {
System.out.println(inLine);
}
inputStream.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doReadTextFile();
}
}
I'm just learning Java, so take it easy on me. My program's objective is to read a text file and output it into another text file in reverse order. The problem is the professor taught us to to deal with strings and reverse it and such, but nothing about importing/exporting files. Instead, he gave us the following sample code which should import a file. The file returns 3 errors: The first two deal with inLine not being a symbol on lines 24 and 25. The last cannot find the symbol doReadTextFile on line 40.
I have no idea how to read this file and make the necessary changes to reverse and output into a new file. Any help is hugely appreciated.
I also had to change the file type from .txt to .rtf. I'm not sure if that affects how I need to go about this.
EDIT I defined inLine and fixed the doReadWritetextFile naming error, which fixed all my compiling errors. Any help on outputting into new file still appreciated!
I'm also aware he gave me bad sample code. It's supposed to be so we can learn troubleshooting, but with no working code to go off of and very extremely knowledge of the language, it's very difficult to see what's wrong. Thanks for the help!
The good practice will be to use a BufferedFileReader
BufferedFileReader bf = new BufferedFileReader(new FileReader(new File("your_file.your_extention")));
Then you can read lines in your file :
// Initilisation of the inLine variable...
String inLine = null;
while((inLine = bf.readLine()) != null){
System.out.println(inLine);
}
To output a file, you can use StringBuilder to hold the file contents:
private static void doReadWriteTextFile()
{
....
StringBuilder sb = new StringBuilder();
while ((inLine = inputStream.readLine()) != null)
{
sb.append(inline);
}
FileWriter writer = new FileWriter(new File("C:\\temp\\test.txt"));
BufferedWriter bw = new BufferedWriter(writer);
w.write(sb.toString());
bw.close();
}

Search and Replace in a file using arraylist, Java

I wrote the below part of the code but I couldn't bind the arraylist with search and replace
so my csv file is as like below
1/1/1;7/6/1
1/1/2;7/7/1
I want to search the file 1.cfg for 1/1/1 and change it to 7/6/1 and 1/1/2 change to 7/7/1 and it goes so on.
Thank you all in advance
It's now only printing in a new file only the last line of the old File
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ChangeConfiguration {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream degistirilecek = new FileInputStream("c:/Config_Changer.csv");
FileInputStream config = new FileInputStream("c:/1.cfg");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(config);
DataInputStream degistir = new DataInputStream(degistirilecek);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader brdegis = new BufferedReader(new InputStreamReader(degistir));
List<Object> arrayLines = new ArrayList<Object>();
Object contents;
while ((contents = brdegis.readLine()) != null)
{
arrayLines.add(contents);
}
System.out.println(arrayLines + "\n");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Couldn't modify this part error is here :(
BufferedWriter out = new BufferedWriter(new FileWriter("c:/1_new.cfg"));
out.write(strLine);
out.close();
}
in.close();
degistir.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You are opening the file for reading when you declare:
BufferedReader br = new BufferedReader(new InputStreamReader(in));
If you know the entire file will fit in memory, I recommend doing the following :
Open the file and read it's contents in memory into a giant string, then close the file.
Apply your replace in one shot to the giant string.
Open the file and write (e.g use a BufferedWriter) out the contents of the giant string, then close the file.
As a side note, your code as posted will not compile. The quality of the responses you receive are correlated with the quality of the question asked. Always include an SCCE with your question to increase the chance of getting a precise answer to your question.
can you elaborate the purpose of the program?
if it is a simple content replacement in a file.
then just read a line and store it in a string. then use string replace method for replacing a text in a string.
eg:
newStrog=oldString.replace(oldVlue,newValue);

Categories