在Java Path-String中使用File.separator和普通/有什么区别?
与双反斜杠\\平台相比,独立性似乎不是原因,因为两个版本都可以在Windows和Unix下运行.
public class SlashTest {
@Test
public void slash() throws Exception {
File file = new File("src/trials/SlashTest.java");
assertThat(file.exists(), is(true));
}
@Test
public void separator() throws Exception {
File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java");
assertThat(file.exists(), is(true));
}
}
Run Code Online (Sandbox Code Playgroud)
要重新解释这个问题,如果/适用于Unix和Windows,为什么要使用File.separator?
我一周前开始使用Java,现在我想在窗口中插入一个图像.无论我尝试什么,我都在Eclipse中继续这样做: javax.imageio.IIOException:无法读取输入文件!
package graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import src.Common;
public class Window extends JFrame
{
public class Panel extends JPanel
{
public void paintComponent(Graphics g)
{
Image img;
try
{
img = ImageIO.read(new File("/logo.jpg"));
g.drawImage(img, 0, 0, this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public Window(String title, int width, int height)
{
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Panel());
this.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
}
我认为代码非常自我解释.我试图用这个 …