Вы можете использовать метод contains () из класса String, чтобы проверить, есть ли в строке пробелы. Но из того, что я понял, вы сталкиваетесь с проблемой при чтении строки с пробелами. Вы должны читать, используя in.nextLine ( )
int num;
num=in.nextInt();
String array[]=new String[num];
for(int i=0;i<num;i++){
array[i]=in.nextLine();
if(array[i].contains(" "))
//contains space
else
System.out.println("buzz");}
импорт java.io.*;
import java.net.*;
public class ConvertURLToFileName{
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the URL : ");
String str = in.readLine();
try{
URL url = new URL(str);
System.out.println("File : "+ url.getFile());
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
я надеюсь, что это поможет Вам.
ответ andy, восстановленный с помощью разделения ():
Url u= ...;
String[] pathparts= u.getPath().split("\\/");
String filename= pathparts[pathparts.length-1].split("\\.", 1)[0];
Создайте объект URL из Строки. Когда сначала у Вас есть объект URL, что существуют методы для легкого вытаскивания примерно любого отрывка информации, Вам нужно.
я могу настоятельно рекомендовать веб-сайт Javaalmanac, который имеет тонны примеров, но который с тех пор переместился. Вы могли бы найти http://exampledepot.8waytrips.com/egs/java.io/File2Uri.html интересный:
// Create a file object
File file = new File("filename");
// Convert the file object to a URL
URL url = null;
try {
// The file need not exist. It is made into an absolute path
// by prefixing the current working directory
url = file.toURL(); // file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}
// Convert the URL to a file object
file = new File(url.getFile()); // d:/almanac1.4/java.io/filename
// Read the file contents using the URL
try {
// Open an input stream
InputStream is = url.openStream();
// Read from is
is.close();
} catch (IOException e) {
// Could not open the file
}
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
Это должно о сокращении он (я оставлю обработку ошибок Вам):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
Я придумал это:
String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));
public static String getFileName(URL extUrl) {
//URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
String filename = "";
//PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
String path = extUrl.getPath();
//Checks for both forward and/or backslash
//NOTE:**While backslashes are not supported in URL's
//most browsers will autoreplace them with forward slashes
//So technically if you're parsing an html page you could run into
//a backslash , so i'm accounting for them here;
String[] pathContents = path.split("[\\\\/]");
if(pathContents != null){
int pathContentsLength = pathContents.length;
System.out.println("Path Contents Length: " + pathContentsLength);
for (int i = 0; i < pathContents.length; i++) {
System.out.println("Path " + i + ": " + pathContents[i]);
}
//lastPart: s659629384_752969_4472.jpg
String lastPart = pathContents[pathContentsLength-1];
String[] lastPartContents = lastPart.split("\\.");
if(lastPartContents != null && lastPartContents.length > 1){
int lastPartContentLength = lastPartContents.length;
System.out.println("Last Part Length: " + lastPartContentLength);
//filenames can contain . , so we assume everything before
//the last . is the name, everything after the last . is the
//extension
String name = "";
for (int i = 0; i < lastPartContentLength; i++) {
System.out.println("Last Part " + i + ": "+ lastPartContents[i]);
if(i < (lastPartContents.length -1)){
name += lastPartContents[i] ;
if(i < (lastPartContentLength -2)){
name += ".";
}
}
}
String extension = lastPartContents[lastPartContentLength -1];
filename = name + "." +extension;
System.out.println("Name: " + name);
System.out.println("Extension: " + extension);
System.out.println("Filename: " + filename);
}
}
return filename;
}