当前位置: 首页 > 知识库问答 >
问题:

无法在src目录下找到文件和图像

洪弘毅
2023-03-14

在我的程序中,src目录下列出了三个文件夹:文件、声音、图像。我不知道为什么我的代码没有被检测到。当我运行这个程序时,我收到了这样一条消息:“java.io.FileNotFoundException:files\7.txt(系统找不到指定的路径)”。我有图片附在这里。请帮忙。

下面是我的代码

package riddle;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;

public class Math_Riddle extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel lblQuestion;
JLabel lblImage;
JButton bOK;
JButton bExit;
JPanel radioPanel;
JPanel panBottom;
JRadioButton[] radioButton;
String [] store ;
ButtonGroup bg;
JButton bNext;
JPanel mainPanel;
JPanel pRight;
JLabel lblCorrect;
JLabel lblWrong;
int vCorrect = 0;
int vWrong = 0;
public Math_Riddle()
{
mainPanel = new JPanel(new BorderLayout());
buildingGUI();
listAllFiles();
innitializeAllComponents();
int fileNumber = generateRandomNumber();
String filePath = "files/" + fileNumber + ".txt";
String strQuestion = readTextFile(filePath);
store = strQuestion.toString().split("!!!");
lblQuestion.setText("<html>" + store[0] + "</html>");
//I need to get the image and display at the center according
//to the fileNumber;
getTheImageAndDisplay(fileNumber);
assignRandomNumberToRadioButton(store[1]);
mainPanel.add(lblQuestion, BorderLayout.NORTH);
mainPanel.add(radioPanel, BorderLayout.WEST);
mainPanel.add(panBottom, BorderLayout.SOUTH);
mainPanel.add(lblImage, BorderLayout.CENTER);
mainPanel.setPreferredSize(new Dimension(640, 480));

this.getContentPane().add(mainPanel);
}

private void listAllFiles()
{
// TODO Auto-generated method stub
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
}

private void getTheImageAndDisplay(int fileNumber)
{
// TODO Auto-generated method stub
String filePath = "images/";
lblImage.setIcon(new ImageIcon(filePath + fileNumber + ".png"));
}

private void assignRandomNumberToRadioButton(String sAnswer)
{
// TODO Auto-generated method stub
int number  = Integer.parseInt(sAnswer.toString().trim());
System.out.println("number: " + number);
Random random = new Random();
int rand = random.nextInt(4); //This is the number of radioButton.
System.out.println("rand is: " + rand);
radioButton[rand].setText(sAnswer);

if(!radioButton[0].getText().equals(""))
{
    radioButton[1].setText("" +( number + 2));
    radioButton[2].setText("" + (number - 2));
    radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[1].getText().equals(""))
{
    radioButton[0].setText("" +( number + 2));
    radioButton[2].setText("" + (number - 2));
    radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[2].getText().equals(""))
{
    radioButton[1].setText("" +( number + 2));
    radioButton[0].setText("" + (number - 2));
    radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[3].getText().equals(""))
{
    radioButton[1].setText("" +( number + 2));
    radioButton[2].setText("" + (number - 2));
    radioButton[0].setText("" + (number + 1));
}
}

/**
* Construct GUI.
*/
private void buildingGUI()
{
lblImage = new JLabel();
bNext = new JButton("Next");
lblQuestion = new JLabel();
bOK = new JButton("OK");
bExit = new JButton("Exit");
lblQuestion.setFont(new Font("Tahoma", Font.PLAIN, 12));
radioPanel = new JPanel();
panBottom = new JPanel();
panBottom.setLayout(new GridLayout(1, 2));
panBottom.add(bOK);
panBottom.add(bExit);
bg = new ButtonGroup();
radioPanel.setLayout(new GridLayout(4, 1));
radioButton = new JRadioButton[4];
radioButton[0] = new JRadioButton();
radioButton[1] = new JRadioButton();
radioButton[2] = new JRadioButton();
radioButton[3] = new JRadioButton();
radioPanel.setLayout(new GridLayout(10, 1));
radioPanel.add(radioButton[0]);
radioPanel.add(radioButton[1]);
radioPanel.add(radioButton[2]);
radioPanel.add(radioButton[3]);
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
radioPanel.add(bNext);
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
bg.add(radioButton[0]);
bg.add(radioButton[1]);
bg.add(radioButton[2]);
bg.add(radioButton[3]);
pRight = new JPanel();
pRight.setLayout(new GridLayout(5, 2));
lblCorrect = new JLabel();
pRight.add(lblCorrect);
lblWrong = new JLabel();
pRight.add(lblWrong);
pRight.add(new JLabel("                   "));
pRight.add(new JLabel("                   "));
mainPanel.add(pRight, BorderLayout.EAST);
}

private int generateRandomNumber()
{
// TODO Auto-generated method stub
Random random = new Random();
int rand = random.nextInt(20);  //This is the number of Files in the system.
return rand;
}

private void innitializeAllComponents()
{
// TODO Auto-generated method stub
CompoundBorder border;
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
border = BorderFactory.createCompoundBorder( raisedbevel, loweredbevel);
lblQuestion.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblQuestion.setBorder(BorderFactory.createLineBorder(Color.GREEN));
lblQuestion.setBorder(border);
radioPanel.setBorder(border);
pRight.setBorder(border);
panBottom.setBorder(border);
radioButton[0].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[1].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[2].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[3].setFont(new Font("Tahoma", Font.BOLD, 16));
lblCorrect.setFont(new Font("Tahoma", Font.BOLD, 14));
lblCorrect.setForeground(Color.BLUE);
lblCorrect.setHorizontalAlignment(JLabel.CENTER);
lblWrong.setFont(new Font("Tahoma", Font.BOLD, 14));
lblWrong.setForeground(Color.red);
lblWrong.setHorizontalAlignment(JLabel.CENTER);
bNext.addActionListener(this);
}
@SuppressWarnings("resource")
private static String readTextFile(String fileName)
{
// TODO Auto-generated method stub
BufferedReader reader;
try
{
    reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String ls = System.getProperty("line.separator");
    try
    {
        while(( line = reader.readLine()) != null )
        {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return stringBuilder.toString();
}
catch (FileNotFoundException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
    return null;
}
}

@Override
public void actionPerformed(ActionEvent ae)
{
// TODO Auto-generated method stub
if(ae.getSource().equals(bNext))
{
    //if nothing selected, display a message,
    //else: get the answer and display.
    if(!radioButton[0].isSelected() && !radioButton[1].isSelected() &&
            !radioButton[2].isSelected() && !radioButton[3].isSelected())
    {
        JOptionPane.showMessageDialog(this,"Please select an Answer.", "Nothing selected",
                JOptionPane.OK_OPTION);
        return;
    }
    else //when user select an answer.
    {
        String strAnswer = "";
        if(radioButton[0].isSelected())
        {
            strAnswer = radioButton[0].getText().trim();
        }
        else if(radioButton[1].isSelected())
        {
            strAnswer = radioButton[1].getText().trim();
        }
        else if(radioButton[2].isSelected())
        {
            strAnswer = radioButton[2].getText().trim();
        }
        else if(radioButton[3].isSelected())
        {
            strAnswer = radioButton[3].getText().trim();
        }
        if(strAnswer.equals(store[1].trim()))
        {
            String strCorrect = lblCorrect.getText();
            if(strCorrect.equals(""))
            {
                strCorrect = "0";
            }
            vCorrect = Integer.parseInt(strCorrect);
            vCorrect = vCorrect + 1;
            lblCorrect.setText("" + vCorrect);
            playSound("correct");
        }
        else
        {
            String strWrong = lblWrong.getText();
            if(strWrong.equals(""))
            {
                strWrong = "0";
            }
            vWrong = Integer.parseInt(strWrong);
            vWrong = vWrong + 1;
            lblWrong.setText("" + vWrong);
            playSound("wrong");
        }
        int fileNumber = generateRandomNumber();
        String filePath = "files\\" + fileNumber + ".txt";
        System.out.println("filePath: " + filePath);
        String strQuestion = readTextFile(filePath);
        store = strQuestion.toString().split("!!!");
        lblQuestion.setText("<html>" + store[0] + "</html>");
        System.out.println("store[0] is: " + store[0]);
        System.out.println("store[1]" + store[1]);
        clearTextInAllRadioButtons();
        assignRandomNumberToRadioButton(store[1]);
        getTheImageAndDisplay(fileNumber);
    }
}
}

private void playSound(String sound)
{
// TODO Auto-generated method stub
try
{
    URL url = null;
    if(sound.equals("correct"))
    {
        url = this.getClass().getClassLoader().getResource("sound/ding.wav");
    }
    else if(sound.equals("wrong"))
    {
        url = this.getClass().getClassLoader().getResource("sound/buzz.wav");
    }
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
    // Get a sound clip resource.
    Clip clip = AudioSystem.getClip();
    // Open audio clip and load samples from the audio input stream.
    clip.open(audioIn);
    clip.start();
}
catch (UnsupportedAudioFileException e)
{
    e.printStackTrace();
}
catch (IOException e)
{
    e.printStackTrace();
}
catch (LineUnavailableException e)
{
    e.printStackTrace();
}
}

private void clearTextInAllRadioButtons()
{
// TODO Auto-generated method stub
radioButton[0].setText("");
radioButton[1].setText("");
radioButton[2].setText("");
radioButton[3].setText("");
bg.clearSelection();
}

/**
* @param args
*/
public static void main(String[] s)
{
Math_Riddle mr = new Math_Riddle();
mr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mr.pack();
mr.setVisible(true);
}
}

关于文件File=新文件(resource.toURI());以下是我尝试过但仍然无效的内容:

URL url = null;
Random rand = new Random();
int random = rand.nextInt(19);
String filePath = "files/" + random + ".txt";
System.out.println("file: " + filePath);
url = this.getClass().getClassLoader().getResource(filePath);
System.out.println(url.toString().trim());
try
{
File file = new File(url.toURI());
}
catch (URISyntaxException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
File folder = new File(".");
for(String fileNames : folder.list())
{
System.out.println(fileNames);
}
BufferedReader reader;
try
{
reader = new BufferedReader(new FileReader(filePath));
String line = null;
StringBuilder  stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try
{
while(( line = reader.readLine()) != null )
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

下面是eclipse中的错误消息:

档案:档案/5。txt文件:/C:/JavaProject/Tesing/bin/files/5。txt。类路径。项目设置bin图像src-java。伊奥。FileNotFoundException:文件\5。txt(系统无法找到指定的路径)在java上。伊奥。文件输入流。在java上打开(本机方法)。伊奥。文件输入流。(来源不详)在java。伊奥。文件输入流。(来源不详)在java。伊奥。文件阅读器。(未知来源)在测试中。执行的操作(Testing.java:72)

当我试图列出所有文件/文件夹时。它只列出了文件夹:bin、images、src。。。。正如你在上面看到的。请帮忙。提前谢谢。

共有1个答案

南门英飙
2023-03-14

您正在用路径指定资源文件。只有当您实际上知道当前目录中的完整路径或相对路径时,这才有效;例如,如另一个答案中建议的那样,前缀为“src”。

不过,最好在构建中包含资源(无论是通过IDE还是通过gradle或maven等外部构建系统构建),以便将这些文件复制到类路径中(可能是您已经在这样做了)。在本例中,您可以使用Java类加载器检索资源,如下所示:

URL resource = getClass().getResource("/path/to/resource");

这里有几个注意事项:

  1. 前导“/”指定类加载器应从根包中搜索。如果是ommitted,它会从你所在的类的包中搜索relative

编辑:以下是一个应该适用于丹尼的例子,基于他的“回答”帖子和一个例子。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class ResourceTest {

    public static void main(String[] args) throws IOException, URISyntaxException {
        new ResourceTest().test();
    }

    public void test() throws URISyntaxException, IOException {
        URL url = getClass().getClassLoader().getResource("files/1.txt");
        System.out.println("URL: " + url);

        File file = new File(url.toURI());
        System.out.println("FILE: " + file);

        File folder = file.getParentFile();
        System.out.println("FOLDER: " + folder);
        System.out.println("FOLDER LIST: ");
        for (String fileName : folder.list()) {
            System.out.println("  " + fileName);
        }

        System.out.println("FILE CONTENTS:");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
    }
}

用于产生以下输出:

URL: file:/home/steinar/Safe/source/private/out/production/files/1.txt
FILE: /home/steinar/Safe/source/private/out/production/files/1.txt
FOLDER: /home/steinar/Safe/source/private/out/production/files
FOLDER LIST: 
  1.txt
FILE CONTENTS:
This is
my test
text file
 类似资料:
  • 我已经将一个 Ruby 项目加载到 RubyMine 中,它的规范文件像往常一样位于目录中。右键单击并选择对任何单个等级库文件的“运行”可以正确运行它。右键单击并选择目录上的“全部运行”会导致每个测试失败并显示以下消息: 无法加载:/Users/Nathaniel/repos/close-web/spec/compositions/analysis/analysis _ data _ spec .

  • 问题内容: 我正在寻找一种方法来获取给定目录中所有目录的名称,而不是文件。 例如,假设我有一个名为的文件夹,并且在其中有3个文件夹: 和。 我想获取文件夹的名称,但不关心内容或Child1,Child2等内的子文件夹的名称。 有没有简单的方法可以做到这一点? 问题答案: 您可以使用列出所有文件名,然后使用循环检查每个子文件并使用函数获取子目录。 例如:

  • 我目前使用eclipse进行Java开发。有人能解释为什么在使用像FileReader这样的类时文件被放在src目录下的原因吗?在使用getClass().getResourceAsStream(“...”)等方法时,有时必须将文件放在bin目录下为了读图像?方法getClass().getResourceAsstream(“...”)有其他方法吗需要src目录下的文件吗?

  • 问题内容: 在Python中,我可以使用哪些命令来查找: 1.当前目录(运行Python脚本时我在终端中的位置) 2.我正在执行的文件在哪里? 问题答案: 要获取包含Python文件的目录的完整路径,请在该文件中写入以下内容: (请注意,如果你已经习惯于更改当前的工作目录,则上述方法将不起作用,因为常量的值是相对于当前的工作目录而言的,并且不会被调用更改。) 要获取当前的工作目录,请使用 上面使用

  • 问题内容: 我从阅读了以下文档,但它说,但是当我将index.html文件放在 字符串下时,才呈现出来。目前在下,我 正在使用。 MvcConfiguration Restful Service for index page 在我的IDE控制台上,我确实看到了 从打印的内容 ,并且在Chrome开发工具中的网络下面看到了该内容,但我只能 看到。 index.html 问题答案: Spring Bo

  • 问题内容: 我正在尝试从dataTable内部的graphicImage更新一个dataTable。我尝试了很多f:ajax渲染值的组合,但是都没有成功,现在我使用的是PrimeFaces的p:component函数,但是之前遇到了相同的错误。我在浏览器中收到此错误: f:ajax包含未知ID’j_idt690:painelTabelaAPDespesa’-无法在组件j_idt735的上下文中找到