使用布尔方法时,我如何将txt文件的字符串内容添加到数组列表中

huangapple go评论79阅读模式
英文:

While using a boolean method, how do I add the String contents of a txt file into an array list

问题

我正试图使用方法 "public boolean readArtists" 结合扫描器从文件中读取字符串,并在成功打开时返回 true。这个方法还应该 "将文件中存储的所有艺术家加入列表"。

我已经了解如何编写一个公共的静态 void 方法来读取文本文件并返回内容:

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);
}

以下是测试部分:

我必须保持方法 "public boolean readArtists(String filename)",所以我的问题是,在这个方法内部,我如何使用扫描器将文本文件的内容读取到 ArrayList 中,同时如果成功打开文件则返回 true。否则,处理异常,显示包含缺失文件名的适当错误消息,然后返回 false。

英文:

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.

答案1

得分: 0

你可以通过以下方式实现,

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); // 文件的完整路径和名称
    return file.canRead();
}
英文:

You can achieve that using,

public static void main(String[] args) throws FileNotFoundException {
		String filepath = &quot;C:\\Users\\Admin\\Downloads\\testFile.txt&quot;;
		List&lt;String&gt; arrayList = new ArrayList&lt;&gt;();
		
		if(readArtists(filepath)) {
			Scanner sc = new Scanner(new File(filepath));
			sc.useDelimiter(&quot;\\A&quot;); 
			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();
	}

答案2

得分: 0

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;
    }
}

这段代码从一个 .txt 文件中读取数据,并将每一行作为一个独立的字符串添加到 ArrayList 中。如果文件不存在,代码会输出 err 文件名 并返回 false;如果文件存在,则返回 true。顺便提一下,你可以在 https://www.w3schools.com/java/java_files.asp 这个网站学习关于 Java 文件处理的知识。

英文:
public class Artists{
public static ArrayList&lt;String&gt; artists = new ArrayList&lt;String&gt;();
public static void main(String[] args) {
	System.out.println(readArtists(&quot;filename goes here&quot;));
    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(&quot;err &quot;+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.

huangapple
  • 本文由 发表于 2020年10月6日 12:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64219287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定