I am attempting to use the method "public boolean readArtists" with a scanner to read strings from a file and return true if opened successfully. This method is also supposed to "Adds to the list all of the artists stored in the file passed parameter."
I've seen how to write the code in a public static void method that will read the text file and return it:
public static void main(String[] args) {
File file = new File("artists30.txt");
String content = null;
try {
try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
content = scanner.useDelimiter("\\A").next();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
Here is the test:
I have to keep the method "public boolean readArtists(String filename), so my question is, within this method, how do I read the contents of the text file into an ArrayList using a scanner, while also returning true if the file is opened successfully, Otherwise, handling the exception, displaying an appropriate error message containing the name of the missing file and return false.
public class Artists{
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("filename goes here"));
System.out.println(artists);
}
public Artists(String artist, String genre)
{
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if(file.createNewFile()) {
System.out.println("err "+fileName);
return false;
}
sc = new Scanner(file);
while(sc.hasNextLine()) {
artists.add(sc.nextLine());
}
}catch(Exception e) {
e.printStackTrace();
}
if(sc!=null) {sc.close();}
return true;
}
}
This answer reads data from a .txt document into an ArrayList, as long as the .txt document names are on seperate lines in the document. It also outputs err \FILE\NAME and returns false if the document does not exist and true if it does. https://www.w3schools.com/java/java_files.asp is a great website to learn java by the way and this link brings you to the file handling page.
You can achieve that using,
public static void main(String[] args) throws FileNotFoundException {
String filepath = "C:\\Users\\Admin\\Downloads\\testFile.txt";
List<String> arrayList = new ArrayList<>();
if(readArtists(filepath)) {
Scanner sc = new Scanner(new File(filepath));
sc.useDelimiter("\\A");
while(sc.hasNext()) {
arrayList.add(sc.next());
}
}
System.out.println(arrayList);
}
public static boolean readArtists(String filename)
{
File file = new File(filename); //full path of the file with name
return file.canRead();
}
enter image description hereI am trying use a text file to read that is in eclipse but it not able to find the text file I put in eclipse.
import java.util.Scanner;
import java.io.*;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner (System.in);
BagBase bb = new BagBase();
System.out.println("Please enter items into the bag: ");
try {
start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void start() throws FileNotFoundException {
BagBase bb = new BagBase();
Scanner sc = new Scanner (System.in);
String wow;
File f = new File("C:/Users/sruja/workspace/Prjocet1/src/ListForBag.txt");
Scanner aa = new Scanner (f);
wow=aa.nextLine();
bb.inserItem(wow);
}
}
Thank for the help.
I was not sure why this link was not find when I put in same project
What do you mean with "a file is in eclipse"?
Is it in a resource folder? What is your project's structure?
If you had the following structure:
MyProject/src/main/java/analysis/ResourceReader.java
MyProject/src/main/resources/text.txt
Then you could access the text.txt file with the following function (pass the name of a file as a parameter to this function):
private static Reader getReaderFromResource(String resourceName) {
URL resource = ResourceReader.class.getClassLoader().getResource(resourceName);
URL url = Objects.requireNonNull(resource);
String decodedStr = URLDecoder.decode(url.getFile(), "UTF-8");
return new FileReader(new File(decodedStr));
}
You could then stuff a BufferedReader constructor with an instance obtained by executing this method (remember about handling exceptions!) and eventually read a file line by line.
EDIT
Ok, so having seen what you're trying to do, I'd go with the following:
Create a project (the best would be a maven project), so that you have a structure similar to the one I've already described. It is a good practice to have resources in a seprate folder in a project, not splitted somewhere on your disk.
This code needs some refactoring, but I don't address it in this answer, for the sake of simplicity.
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
BagBase bb = new BagBase();
System.out.println("Please enter items into the bag: ");
try {
start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void start() throws FileNotFoundException {
BagBase bb = new BagBase();
Scanner sc = new Scanner(System.in);
String wow;
List<String> dataFromFile = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(getReaderFromResource("shoppingList"))) {
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine); // prints content of a file, just for the record
dataFromFile.add(currentLine);
}
bb.setBag(dataFromFile);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Reader getReaderFromResource(String resourceName) throws FileNotFoundException, UnsupportedEncodingException {
URL resource = test.class.getClassLoader().getResource(resourceName);
URL url = Objects.requireNonNull(resource);
String decodedStr = URLDecoder.decode(url.getFile(), "UTF-8");
return new FileReader(new File(decodedStr));
}
}
This fails with FileNotFoundException in new Scanner(file):
public class Ex1 {
public static void main(String[] args) {
// boot.txt -is in its own "resource" source folder in Eclipse
String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
File file = new File(fileName); // File (String pathname) ctor
Scanner sc;
try {
sc = new Scanner(file); // FileNotFoundException here
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
But this runs fine without any Exception (class in same package):
public class Ex2 {
public static void main(String[] args) {
URL fileURL = Ex2.class.getResource("/boot.txt");
Scanner sc;
try {
File file = new File(fileURL.toURI());
sc = new Scanner(file); // fine!
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
}
What is wrong with
String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
File file = new File(fileName);
Scanner sc = new Scanner(file);
This contributes to "strange" differences between Scanner ctors, but does not answer this question...
I have 4 different files in some locations like:
D:\1.txt
D:\2.txt
D:\3.txt and
D:\4.txt
I need to create a new file as NewFile.txt, It should contains all the contents present in the above files 1.txt, 2.txt,3.txt 4.txt.......
All Data should present in the New Single file(NewFile.txt)..
Please suggest me some idea to do the same in java or Groovy....
Here's one way to do it in Groovy:
// Get a writer to your new file
new File( '/tmp/newfile.txt' ).withWriter { w ->
// For each input file path
['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->
// Get a reader for the input file
new File( f ).withReader { r ->
// And write data from the input into the output
w << r << '\n'
}
}
}
The advantage of doing it this way (over calling getText on each of the source files) is that it will not need to load the entire file into memory before writing its contents out to newfile. If one of your files was immense, the other method could fail.
This is in groovy
def allContentFile = new File("D:/NewFile.txt")
def fileLocations = ['D:/1.txt' , 'D:/2.txt' , 'D:/3.txt' , 'D:/4.txt']
fileLocations.each{ allContentFile.append(new File(it).getText()) }
i am showing you the way it is to be done in java:
public class Readdfiles {
public static void main(String args[]) throws Exception
{
String []filename={"C:\\WORK_Saurabh\\1.txt","C:\\WORK_Saurabh\\2.txt"};
File file=new File("C:\\WORK_Saurabh\\new.txt");
FileWriter output=new FileWriter(file);
try
{
for(int i=0;i<filename.length;i++)
{
BufferedReader objBufferedReader = new BufferedReader(new FileReader(getDictionaryFilePath(filename[i])));
String line;
while ((line = objBufferedReader.readLine())!=null )
{
line=line.replace(" ","");
output.write(line);
}
objBufferedReader.close();
}
output.close();
}
catch (Exception e)
{
throw new Exception (e);
}
}
public static String getDictionaryFilePath(String filename) throws Exception
{
String dictionaryFolderPath = null;
File configFolder = new File(filename);
try
{
dictionaryFolderPath = configFolder.getAbsolutePath();
}
catch (Exception e)
{
throw new Exception (e);
}
return dictionaryFolderPath;
}
}
tell me if you have any doubts
I tried solving this and i found its quite easy if you copy the contents to an array and write the array to a different file
public class Fileread
{
public static File read(File f,File f1) throws FileNotFoundException
{
File file3=new File("C:\\New folder\\file3.txt");
PrintWriter output=new PrintWriter(file3);
ArrayList arr=new ArrayList();
Scanner sc=new Scanner(f);
Scanner sc1=new Scanner(f1);
while(sc.hasNext())
{
arr.add(sc.next());
}
while(sc1.hasNext())
{
arr.add(sc1.next());
}
output.print(arr);
output.close();
return file3;
}
/**
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) {
try
{
File file1=new File("C:\\New folder\\file1.txt");
File file2=new File("C:\\New folder\\file2.txt");
File file3=read(file1,file2);
Scanner sc=new Scanner(file3);
while(sc.hasNext())
System.out.print(sc.next());
}
catch(Exception e)
{
System.out.printf("Error :%s",e);
}
}
}
You can do something like this in Java. Hope it helps you resolve your problem:
import java.io.*;
class FileRead {
public void readFile(String[] args) {
for (String textfile : args) {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
// Write to the new file
FileWriter filestream = new FileWriter("Combination.txt",true);
BufferedWriter out = new BufferedWriter(filestream);
out.write(strLine);
//Close the output stream
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public static void main(String args[]) {
FileRead myReader = new FileRead();
String fileArray[] = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"};
myReader.readFile(fileArray);
}
}
One liner example:
def out = new File(".all_profiles")
['.bash_profile', '.bashrc', '.zshrc'].each {out << new File(it).text}
OR
['.bash_profile', '.bashrc', '.zshrc'].collect{new File(it)}.each{out << it.text}
Tim's implementation is better if you have big files.
public static void main(String[] args) throws IOException {
List<String> files=new ArrayList<String>();
for(int i=10;i<14;i++)
files.add("C://opt/Test/test"+i+".csv");
String destFile ="C://opt/Test/test.csv";
System.out.println("TO "+destFile);
long st=System.currentTimeMillis();
mergefiles(files, destFile);
System.out.println("DONE."+(st-System.currentTimeMillis()));
}
public static void mergefiles(List<String> files,String destFile){
Path outFile = Paths.get(destFile);
try(FileChannel out=FileChannel.open(outFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
for(String file:files) {
Path inFile=Paths.get(file);
System.out.println(inFile);
try(FileChannel in=FileChannel.open(inFile, StandardOpenOption.READ)) {
for(long p=0, l=in.size(); p<l; )
p+=in.transferTo(p, l-p, out);
}catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
out.write(ByteBuffer.wrap("\n".getBytes()));
}
} catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
}
I have a little problem here.
I am declaring a new object "Fleet" in these methods:
public void run() throws FileNotFoundException
{
File file = new File(getFile());
Fleet fleet = new Fleet(file);
buildFleet(file, fleet);
}
private void buildFleet(File file, Fleet fleet) throws FileNotFoundException
{
fleet.addVehicle(Honda);
userMenu(fleet);
}
The last line calls the userMenu() method. In this method I need to be able to change the value of "File" inside Fleet without creating a new instance of the class.
private void userMenu(Fleet fleet) throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
fleet = new Fleet(file);
this.createMenu();
choice = this.menu.getChoice();
while(choice != 8)
{
switch(choice)
{
case 1:
//Do stuff
fleet.addVehicle(Honda);
break;
}
}
Also, I am not allowed to create any new class level data.
Any suggestions?
What about a setter on your Fleet class for the file:
public class Fleet {
private File file;
...
public void setFile( File file ){
this.file = file;
}
}
You can then call this method to change the file inside your fleet object by calling
fleet.setFile( myNewFile );
Solved:
I changed:
private void userMenu() throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
to:
private void userMenu(Fleet fleet) throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
fleet.file = file;