I have this FileIO class which reads a .txt file and stores them into a String ArrayList. However when i tried to print out the contents of my arrayList, it appears to be empty. Where have i made an error?
public class FileIO
{
public ArrayList<String> readFile() throws IOException
{
ArrayList<String> al = new ArrayList<String>();
try
{
File file = new File("example.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null)
{
al.add(line);
}
fileReader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println();
for (int i = 0; i < al.size(); i++)
{
System.out.println(al.get(i));
}
return al;
}
}
public class Main
{
public static void main(String[] args)
{
FileIO fileIO = new FileIO();
ArrayList<String> temp = fileIO.readFile();
}
}
The contents of my txt file is just:
this is text1
this is text2
this is text3
Most probable reason for not getting data is that you haven't set the file path correctly. And below line is not necessary for this.
File file = new File("example.txt");
You can directly create a FileReader object from the file name as below.
FileReader fileReader = new FileReader("example.txt);
Related
I want to read a text file. For this I am giving a path of the file but its not getting read.
Giving error like : ClassLoader referenced unknown path: /data/app/com.kiranaapp-1/lib/arm
I have saved the text file in helper folder of an app.
public void ReadFile() {
try {
BufferedReader in = new BufferedReader(new FileReader("E:/siddhiwork/KiranaCustomerApp/app/src/main/java/com/kiranacustomerapp/helper/itemNames.txt"));
String str;
List<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
}
catch (FileNotFoundException e)
{
System.out.print(e);
}
catch (IOException e)
{
System.out.print(e);
}
}
As I debug to see if file is getting read and strings are stored in an array,
but nothing happens.
Help please , Thank you..
Edit :
My attempt to get strings in list, not getting any value in itemList
public class StartupActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> itemList = new ArrayList<>();
itemList = readRawTextFile(StartupActivity.this);
}
public static List<String> readRawTextFile(Context context) {
String sText = null;
List<String> stringList;
try{
InputStream is = context.getResources().openRawResource(R.raw.item_names);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
stringList = new ArrayList<String>(Arrays.asList(sText.split(" ")));
System.out.print(stringList);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return stringList;
}
}
You should not give a file path to the computer path. Store file either in assets folder or in raw folder then fetch from there in android.
public String loadTextFromFile() {
String sText = null;
try {
//If your file is in assets folder
InputStream is = getAssets().open("file_name.txt");
//If your file is in raw folder
InputStream is = getResources().openRawResource(R.raw.file_name);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return sText;
}
To split text with "," format:
String[] sTextArray = sText.replace("\"", "").split(",");
List<String> stringList = new ArrayList<String>(Arrays.asList(sTextArray));
First of all, Put the file in raw directory under res directory.
Now try below code to read file,
public static String readRawTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
ArrayList<String> lineList = new ArrayList<>();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
lineList.add(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
// Use your arraylist here, since its filled up.
return text.toString();
}
If the file is generated dynamically in cache, you can
File file = getCacheDir() + "FOLDER_PATH_WITH_FILENAME";
Otherwise, save the file in assets folder inside main directory.
main
-----> java
-----> res
-----> assets
-----> AndroidManifest.xml
then, get file using:
InputStream inputStream = getAssets().open("FILE_NAME");
I have a file that has data inside of it. In my main method I read in the file and closed the file. I call another method that created a new file inside of the same folder of the original file. So now I have two files, the original file and the file that is being made from the method that I call. I need another method that takes the data from the original file and writes it to the new file that is created. How do I do that?
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException {
String filename = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
File textFile = new File(filename);
Scanner in = new Scanner(textFile);
in.close();
newFile();
}
public static void newFile() {
final Formatter x;
try {
x = new Formatter("/Users/DAndre/Desktop/Alice/new1.text");
System.out.println("you created a new file");
} catch (Exception e) {
System.out.println("Did not work");
}
}
private static void newData() {
}
}
If your requirement is to copy your original files content to new file. Then this may be a solution.
Solution:
First, read to your original file using BufferedReader and pass your content to another method which creates new file using PrintWriter. and add your content to your new file.
Example:
public class CopyFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("C:\\Users\\yubaraj\\Desktop\\wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\yubaraj\\Desktop\\new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have two classes:
class actUI
public class ActUI extends javax.swing.JFrame{
//there are the other classes here
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (Object s : list) {
out.write((String) s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
UniqueLineReader ULR = new UniqueLineReader();
ULR.setFileName(path);
}
//there are the other classes here
}
Class UniqueLineReader:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
private Reader arg0;
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public void setFileName(String filePath){
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
PrintWriter outFile2 = new PrintWriter(new File("result.txt"));
String result = "";
List data = new ArrayList();
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
data.add(strLine);
}
writeToFile(data, "result.txt");
// Close the input stream
//in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I want to acces UniqueLineReader from writeToFile method in actUI, but my code is not working, how can i do that with no error?, help me please.
Take a look at your code.
UniqueLineReader ULR = new UniqueLineReader(); // invalid constructor
ULR.setFileName(path);
There is no matching constructor for this. If you want to access writeToFile() from ActUI, Just change access modifier of writeToFile() to public now you can use following
UniqueLineReader.writeToFile(new ArrayList(), path);
I'm trying to read and display the content of a group of txt files in specific folder with Java. I'm getting error in line with BufferedRead class. What I'm doing wrong?
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
public class DirectoryShow {
public static void main(String[] args) throws IOException {
File f = new File("D:\\Files"); // current directory
File[] files = f.listFiles();
for (File file : files) {
BufferedReader br = new BufferedReader("D:\\Files");
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.print(" file:");
System.out.println(file.getCanonicalPath());
}
}
}
There are two errors:
The first is that where you wrote
BufferedReader br = new BufferedReader("D:\\Files");
that doesn't specify a single file; you probably mean
new BufferedReader(new InputStreamReader(new FileInputStream(file)));
The second error is that it might not the case that every file in the folder is a file, is accessible for reading, etc. In a well-designed application you should check for those things.
public class DirectoryShow {
public static void main(String[] args) throws IOException {
File f = new File("D:\\Files"); // current directory
File[] files = f.listFiles();
for (File file : files) {
BufferedReader br = new BufferedReader(new InputstreamReader(new FileInpupStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
System.out.print(" file:");
System.out.println(file.getCanonicalPath());
}
}
}
I am trying to open a file through the following programcode
public void actionPerformed(ActionEvent e)
{
else if(e.getSource() == menyFlikTre)
{
läsInFil(textFalt.getText());
}
private void läsInFil(String filename)
{
try {
FileReader r = new FileReader(filename);
textArea.read(r, null);
}
catch(IOException e){}
}
When i put in the name of the file with the .txt extension, it only adds the entire name of the file including the extension .txt instead of the content of the file.
You should loop thorough the content of the file and add it to the textArea :
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
// write to textArea
}
private void läsInFil(String filename)
{
try {
File file = new File(filename);
FileReader r = new FileReader(filename);
char[] buf = new char[(int)file.length()];
r.read(buf);
String contentString = new String(buf);
textArea.append(contentString);
}
catch(IOException e){
e.printStacktrace();
}
}